I have just started programming with flutter, and tried to retrieve the time,icon and temp variables from the following file, so far, without success I would welcome any help you could offer.
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;
}
}
}
and fetch data here ..
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); }, ); }, ),
Error
NoSuchMethodError: The getter 'length' was called on null.
I think your forgot to get your hourly
object before data
array.
final hourly = jsonData['hourly'];
final data = hourly['data'];
should work
Ok few changes:
Change the type of your fields :
class Hourly {
int time;
String icon;
String temp;
Hourly({this.time, this.icon, this.temp});
}
And update your method to return cast temp
to 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;
}
}
Your code fixed:
https://gist.github.com/diegoveloper/c53b4a3158f2ed710a089a830ed2e4b5
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.