【问题标题】:How to get data from url Json array in flutter?如何在颤动中从 url Json 数组中获取数据?
【发布时间】:2018-12-12 19:16:25
【问题描述】:

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

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 上调用了 getter 'length'。

【问题讨论】:

  • 还有……有什么错误?
  • 我没有得到任何数据
  • 你调试了吗?打印最终数据的结果是什么 = jsonData['data']; print("数据:${data.length}");
  • NoSuchMethodError: 在 null 上调用了 getter 'length'。

标签: json dart flutter


【解决方案1】:

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

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

应该工作

好的一些变化:

更改字段的类型:

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

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

并更新您的方法以将演员 temp 返回到字符串

    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

【讨论】:

  • 您的服务的网址是什么?我想检查
  • 它为我工作,你得到什么错误?你在用我的代码吗?使用您的最新代码更新您的问题
  • 记得我改了 var final dataHourly = jsonData['hourly'];
猜你喜欢
  • 2020-05-12
  • 2019-04-20
  • 2022-10-22
  • 1970-01-01
  • 2019-12-25
  • 2021-03-10
  • 2021-03-21
  • 2021-05-19
  • 2021-03-26
相关资源
最近更新 更多