Я новичок в флаттере и следовал небольшому руководству по получению ответа Json от простого Json. Теперь я хочу получать данные о погоде из более сложного API. Это проект, который я сделал в Kotlin, он отлично работает, и я просто хочу посмотреть, как он работает во Flutter, но у меня возникают некоторые проблемы с преобразованием ответа в класс. (извините, если моя терминология не совсем правильная).
Мой json метод таков:
_loadData() async {
String weatherURL = "https://api.openweathermap.org/data/2.5/onecall?lat=33.441792&lon=-94.037689&exclude=hourly,daily,minutely&appid=myapikey";
http.Response response = await http.get(weatherURL);
setState(() {
final Map<String, dynamic> weathersJSON = json.decode(response.body);
log(weathersJSON.toString());
List<dynamic> data = weathersJSON[WeatherData];
print(data[0]["lat"]);
for(var weatherJSON in weathersJSON) {
final weatherData = WeatherData(weatherJSON["lat"], weatherJSON["lon"], weatherJSON["timezone"], weatherJSON["timezone_offset"], weatherJSON["current"]);
_weatherDatas.add(weatherData);
}
});
}
И мой ответ API выглядит примерно так:
{"lat":33.44,
"lon":-94.04,
"timezone":"America/Chicago",
"timezone_offset":-18000,
"current":
{"dt":1594400068,
"sunrise":1594379674,
"sunset":1594430893,
"temp":303.95,
"feels_like":306.84,
"pressure":1018,
"humidity":62,
"dew_point":295.83,
"uvi":11.81,
"clouds":20,
"visibility":16093,
"wind_speed":3.1,
"wind_deg":260,
"weather":[
{"id":801,
"main":"Clouds",
"description":"few clouds",
"icon":"02d"}
]
}
}
Сначала я хотел сделать что-то простое, например 'final weathers JSON = json .decode (response.body);', но я получал эту ошибку
Unhandled Exception: type '_InternalLinkedHashMap 'не является подтипом типа' Iterable '
Поэтому я добавил карту на основе другого вопроса стека, потому что он, по-видимому, помогает биту списка погоды в конце Json, и ошибка идет прочь.
Однако сейчас я просто немного застрял. Я хочу добавить всю эту информацию API в класс, который будет использоваться в другом месте приложения. Я составил список типа WeatherData с именем _weatherDatas. Последняя ошибка, с которой я имею дело, - это
Необработанное исключение: NoSuchMethodError: метод '[]' был вызван с нулевым значением.
Я был бы очень признателен за любой совет у вас есть.
Также вот мои классы данных:
class WeatherData {
final double lat;
final double lon;
final String timezone;
final int timezone_offset;
final Current current;
WeatherData(this.lat, this.lon, this.timezone, this.timezone_offset, this.current);
}
class Weather {
final int id;
final String main;
final String description;
final String icon;
Weather(this.id, this.main, this.description, this.icon);
}
class Current {
final int dt;
final int sunrise;
final int sunset;
final double temp;
final double feels_like;
final int pressure;
final int humidity;
final double dew_point;
final double uvi;
final int clouds;
final int visibility;
final double wind_speed;
final int wind_deg;
final List<Weather> weather;
Current(this.dt, this.sunrise, this.sunset, this.temp, this.feels_like, this.pressure, this.humidity,
this.dew_point, this.uvi, this.clouds, this.visibility, this.wind_speed, this.wind_deg, this.weather);
}
ПРИВЕТСТВУЕТ: D