I have calling data from and store in a List which I have defined is a list of model. But still its show error that it's List
My code
class TeamsController with ChangeNotifier {
List<TeamID> teamslist = [];
TeamsController() {
getMyTeams();
}
getMyTeams() async {
var response = await ApiService().getMyCreatedTeams();
if (response != null) {
final databody = json.decode(response);
debugPrint(databody['data'].toString());
teamslist =
databody['data'].map((item) => TeamID.fromJson(item)).toList();
notifyListeners();
}
}
}
Its showing error on teams list that _TypeError (type 'List' is not a subtype of type 'List')
Its working if I first store in list like this
final List list = databody['data'];
teamslist = list.map((item) => TeamID.fromJson(item)).toList();
CodePudding user response:
You can assign your main list as List<dynamic>
like this:
class TeamsController with ChangeNotifier {
List<dynamic> teamslist = [];
TeamsController() {
getMyTeams();
}
getMyTeams() async {
var response = await ApiService().getMyCreatedTeams();
if (response != null) {
final databody = json.decode(response);
debugPrint(databody['data'].toString());
teamslist =
databody['data'].map((item) => TeamID.fromJson(item)).toList();
notifyListeners();
}
}
}
That would work but if you want to know the type then you can first check the type and then assign the type to it. You can the type like this:
print(databody['data'].map((item) => TeamID.fromJson(item)).toList().runtimeType);
After that you can assign teamslist
to that type.
CodePudding user response:
The code you have shown looks reasonable. Given this
List<TeamID> teamslist = [];
...
teamslist =
databody['data'].map((item) => TeamID.fromJson(item)).toList();
Dart's type inference will type this assignment as you're expecting provided that TeamID.fromJson()
's return type is TeamID
.
So please either check your definition of TeamID.fromJson()
or post its code in your question.
(Note, there is no compelling reason to use dynamic
in this case.)