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();
2
Answers
You can assign your main list as
List<dynamic>
like this: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:
After that you can assign
teamslist
to that type.The code you have shown looks reasonable. Given this
Dart’s type inference will type this assignment as you’re expecting provided that
TeamID.fromJson()
‘s return type isTeamID
.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.)