我刚刚开始使用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上调用了吸气剂“长度”。
答案 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