如何从Flutter中的URL Json数组获取数据?

时间:2018-12-12 19:16:26

标签: json dart flutter

我刚刚开始使用flutter进行编程,并尝试从以下文件中检索时间,图标和临时变量,到目前为止,如果没有成功,我将欢迎您提供任何帮助。

enter image description here

class Hourly {
  String time;
  String icon;
  int temp;

  Hourly({this.time, this.icon, this.temp});
}

class Network {
  String url = "************";
  List<Hourly> hourly = [];

  Future<List<Hourly>> fetchHourly() async {
    final res = await http.get(url, headers: {"Accept": "aplication/json"});
    final jsonData = json.decode(res.body);
final hourly = jsonData['hourly'];
final data = hourly['data'];
    for (var h in data) {
      Hourly hour =
          new Hourly(time: h['time'], icon: h['icon'], temp: h['temperature']);
      hourly.add(hour);
    }
    if (res.statusCode == 200) {
      return hourly;
    }
  }
}

并在此处获取数据。

            FutureBuilder(
              future: Network.fetchHourly(),
              builder: (BuildContext context, AsyncSnapshot snap) {
                  return ListView.builder(
                    itemCount: snap.data.length,
                    itemBuilder: (BuildContext context, int i) {
                      return new HourlyItem(snap.data[i].icon,
                          snap.data[i].time, snap.data[i].temp);
                    },
                  );
                
              },
            ),

错误

NoSuchMethodError:在null上调用了吸气剂“长度”。

1 个答案:

答案 0 :(得分:2)

我认为您忘记在hourly数组之前获取data对象。

 final hourly = jsonData['hourly'];
 final data = hourly['data'];

应该工作

好的更改:

更改字段的类型:

  class Hourly {
    int time;
    String icon;
    String temp;

    Hourly({this.time, this.icon, this.temp});
  }

并更新您的方法以将强制转换temp返回给String

    Future<List<Hourly>> fetchHourly() async {
        final res = await http.get(url, headers: {"Accept": "aplication/json"});
        final jsonData = json.decode(res.body);
        final dataHourly = jsonData['hourly'];
        final data = dataHourly['data'];
        for (var h in data) {
          Hourly hour =
              new Hourly(time: h['time'], icon: h['icon'], temp: h['temperature'].toString());
          hourly.add(hour);
        }
        if (res.statusCode == 200) {
          return hourly;
        }
      }

您的固定代码:

https://gist.github.com/diegoveloper/c53b4a3158f2ed710a089a830ed2e4b5