I am trying to write a model but i keep getting this error. Here is the code.
import 'package:flutter/material.dart';
class CardModel {
late List<CardResults> results;
CardModel({ required this.results});
CardModel.fromJson(Map<String, dynamic> json) {
if (json['cardResults'] != null) {
results = List<CardResults>();
json['cardResults'].forEach((v) {
results.add(CardResults.fromJson(v));
});
}
}
}
3
Answers
Since you are getting the list of results from a JSON, you can map get the model list like this:
First,
List
type doesn’t have a default constructor so doingList()
is not possible. So, instead you can create an empty list using<CardResults>[]
orList<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:You can learn more about
map
method here.Third, instead of marking a property as
late
you can make itfinal
and usefactory constructor
to instantiate an object. Finally, yourCardModel
should look like this:You can learn more about factory constructors here.
List<CardResults>()
is no longer valid Dart code as of Dart 3.0.See https://github.com/dart-lang/sdk/issues/49529 for details.
You can instead use
<CardResults>[]
. But personally, I prefer creating the completed list at the declaration, rather than creating an empty list and building it up.