1

我的程序中的“fromJson”有问题。我从服务器取回我的 json 数据。但我无法将它们保存在数组中并将它们返回到我的屏幕。

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());
    }
  }

我的 InfoModel.dart 是这样的:

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"],
      ...
    );
  }
}

此代码适用于 sdk:">=2.7.0 <3.0.0" btu 不适用于 sdk:'>=2.12.0 <3.0.0'。

谢谢

4

0 回答 0