如何在颤振中正确地使用asyncsnapshot从json对象获取列表?

时间:2019-08-25 08:33:36

标签: json flutter dart

我从openweathermap.org获取json api,并使用FutureBuilder来设置文本小部件。

这是json结构:

{
"message": "accurate",
"cod": "200",
"count": 1,
"list": [
{
"id": 113646,
"name": "Tabriz",
"coord": {
"lat": 38.0758,
"lon": 46.2892
},
"main": {
"temp": 29,
"pressure": 1020,
"humidity": 20,
"temp_min": 29,
"temp_max": 29
},
"dt": 1566716943,
"wind": {
"speed": 2.1,
"deg": 80
},
"sys": {
"country": "IR"
},
"rain": null,
"snow": null,
"clouds": {
"all": 20
},
"weather": [
{
"id": 801,
"main": "Clouds",
"description": "few clouds",
"icon": "02d"
}
]
}
]
}

所以我要做的是:

    Future<Map> getJson(String appId, String city) async {
      String url =
          "https://api.openweathermap.org/data/2.5/find?q=$city&units=metric&appid=${util.appId}";
      http.Response response = await http.get(url);
      return json.decode(response.body);
    }

    Widget updateTemp(String city){
      return new FutureBuilder(
          future: getJson(util.appId, city),
          builder:(BuildContext context , AsyncSnapshot<Map> snapshot){
            if(snapshot.hasData){

              Map content = snapshot.data;
              List cont = content['list'];

              return new Container(
                child: Column(
                  children: <Widget>[
                    new ListTile(
                      title: new Text("${cont['main']['temp']}",
                      style: tempStyle(),),
                    ),
                  ],
                ),
              );
            }else{
              return new Container();
            }
          }
      );
    }

为什么我在['main']中收到错误消息,提示无法将参数类型字符串分配给参数类型int? 我认为问题出在

List cont = content['list'];

我正确地获得了['list']吗?

1 个答案:

答案 0 :(得分:0)

尝试将cont['main']['temp']替换为cont.first['main']['temp']。您未指定要访问的元素的索引。