i have a problem with "fromJson" in my program. I get my json data back from the server. But I can't save them in an array and return them to my screen.
static Future<List<Infos>?> getTasks() async {
List<Info> infos= <Info>[];
try{
final http.Response response = await http.get(
Uri.parse('example.com/test.php'),
headers: <String, String> {
'Content-Type': 'application/json; charset=UTF-8',
},
);
// I have here my json-data like
// [{...}, {...}, {...}, ...]
var jsonData = json.decode(response.body);
jsonData.forEach((item) {
infos.add(Info.fromJson(item));
});
// but after foreach I have no data and no error. I think that the foreach causes errors because
// the program does not continue at this point.
return Future<List<Info>>.value(infos);
} on Exception catch (e) {
print(e.toString());
}
}
My InfoModel.dart is like this:
class Info {
String userId;
String infoId;
...
Info({
required this.userId,
required this.infoId,
...
});
factory Info.fromJson(Map<String, dynamic> json) {
return Info(
userId: json["UserId"],
taskId: json["InfoId"],
...
);
}
}
This code works with sdk: ">=2.7.0 <3.0.0" btu not with sdk: '>=2.12.0 <3.0.0'.
Thanks
I had a similar issue, but after wrapping call to
Object.fromJson(json)
withtry
/catch
I was able to see that types were wrong (i.e. "type 'Null' is not a subtype of type 'int'"). Perhaps this can help someone.