0

I'm creating a modal class for calling API and I got an error

The default 'List' constructor isn't available when null safety is enabled. Try using a list literal, 'List.filled' or 'List.generate'.

I studied some answers on StackOverflow but I don't understand the answer.

class Autogenerated {
  bool? status;
  String? message;
  List<Data>? data;

  Autogenerated({required this.status,required this.message,required this.data});

  Autogenerated.fromJson(Map<String, dynamic> json) {
    status = json['status'];
    message = json['message'];
    if (json['data'] != null) {
      data = new List<Data> (); ///error List<Data>()
      json['data'].forEach((v) {
        data?.add(new Data.fromJson(v));
      });
    }
  }
///other code
}
Kodala Parth
  • 243
  • 1
  • 2
  • 12
  • 1
    List constructor can be still used as `List.empty(growable: true)`, but you can also use a shorthand `[]` as mentioned below by Ojan. – GoodSp33d Jul 19 '21 at 06:58
  • Instead of using `.forEach` , you can do: `data = [for (var v in json['data']) Data.fromJson(v)];`. – jamesdlin Jul 19 '21 at 08:34

1 Answers1

2

just change it this way

class Autogenerated {
  bool? status;
  String? message;
  List<Data>? data;

  Autogenerated({required this.status,required this.message,required this.data});

  Autogenerated.fromJson(Map<String, dynamic> json) {
    status = json['status'];
    message = json['message'];
    if (json['data'] != null) {
      data = []; 
      json['data'].forEach((v) {
        data?.add(new Data.fromJson(v));
      });
    }
  }
///other code
}
Ardeshir ojan
  • 1,914
  • 1
  • 13
  • 36