我正在用flutter制作一个简单的天气应用程序,我使用http包从API获取天气信息。我正在将JSON解析为Dart类,这样我就可以在另一个屏幕上显示它。
这是天气预报类
class FivedayForecastData {
String cod;
int message;
int cnt;
List<ListElement> list;
City city;
FivedayForecastData({
required this.cod,
required this.message,
required this.cnt,
required this.list,
required this.city,
});
factory FivedayForecastData.fromJson(Map<String, dynamic> json) => FivedayForecastData(
cod: json["cod"],
message: json["message"],
cnt: json["cnt"],
list: List<ListElement>.from(json["list"].map((x) => ListElement.fromJson(x))),
city: City.fromJson(json["city"]),
);
Map<String, dynamic> toJson() => {
"cod": cod,
"message": message,
"cnt": cnt,
"list": List<dynamic>.from(list.map((x) => x.toJson())),
"city": city.toJson(),
};
}
It says that .map() was called on null even though this 'list' field is not null in the API
这是从API获取数据的函数
required double lattitude,
required double longitude,
}) async {
final link =
'https://api.openweathermap.org/data/2.5/weather?lat=$lattitude&lon=$longitude&appid=$apiKey&units=metric';
final result = await http.get(Uri.parse(link));
if (result.statusCode == 200) {
final data = fivedayForecastDataFromJson(result.body.toString());
// print(data);
return data;
}
}
Part of the JSON data from the API
我仍然在学习和弄清楚http和flutter在geenral的事情,我试图使这个列表为空,只是为了让应用程序运行,但它总是默认为空列表It always defaults to the empty list []
1条答案
按热度按时间6ovsh4lw1#
像这样更新代码