如何在颤振中更改对地图的响应类型

How to change to type of response to Map in flutter

我尝试从 Flutter 到 Nodejs 进行 GET http 调用。我得到的数据是 json 形式,但是当我尝试用 flutter 操作它时我不能,因为响应是 RESPONSE 类型或者我可以将它更改为 string 我不不知道如何将 response 更改为键入 Map 以帮助我处理我获得的数据。

这里是代码:

Future getYear() async {
    var url = "http://192.168.1.19:3000/getyear";
    var response = await http.get(Uri.parse(url));
    var jsonresponse = await json.decode(json.encode(response.body));
  }

这里是我得到的数据,但我无法操纵它[{"year":2019},{"year":2020}]

jsonDecode(response.body) 解码对 Map<String,dynamic> 的响应。

您可以为其创建一个 class,如下所示:

class Year {
  int year;

  Year({this.year});

  Year.fromJson(Map<String, dynamic> json) {
    year = json['year'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['year'] = this.year;
    return data;
  }
}

比你简单的打电话

Year.fromJson(jsonresponse)