First, List
type doesn't have a default constructor so doing List()
is not possible. So, instead you can create an empty list using <CardResults>[]
or List<CardResults>.empty()
.
You can learn more about available constructors for List
type here.
Second, you can optimize your code and instead of creating an empty list and calling add for each item you can use map
method, like:
CardModel.fromJson(Map<String, dynamic> json) {
if (json['cardResults'] != null) {
results = json['cardResults'].map<CardResults>((v) => CardResults.fromJson(v)).toList();
}
}
You can learn more about map
method here.
Third, instead of marking a property as late
you can make it final
and use factory constructor
to instantiate an object. Finally, your CardModel
should look like this:
class CardModel {
final List<CardResults> results;
CardModel({required this.results});
factory CardModel.fromJson(Map<String, dynamic> json) {
return CardModel(
results: json['cardResults']?.map<CardResults>((v) => CardResults.fromJson(v)).toList() ?? [],
);
}
}
You can learn more about factory constructors here.