简体   繁体   中英

Fromjson returns no data in my Flutter App

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) with try / catch I was able to see that types were wrong (ie "type 'Null' is not a subtype of type 'int'"). Perhaps this can help someone.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM