json - 在 null 上调用了方法“[]”-Flutter
问题描述
我想从 api 访问天气数据。json是这样的: jsoncode
我的代码的相关部分是这样的:
Future getWeather() async {
http.Response response = await http.get(
"http://api.openweathermap.org/data/2.5/onecall?lat=$lat&lon=$long&exclude=alerts&appid=apikey");
var results = jsonDecode(response.body);
setState(() {
this.temp = results['current']['temp'];
this.name = results['timezone'];
this.humidity = results['current']['humidity'];
this.description = results['current']['main'];
});
}
这是我得到的错误:
E/flutter ( 9740): [ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: NoSuchMethodError: The method '[]' was called on null.
E/flutter ( 9740): Receiver: null
E/flutter ( 9740): Tried calling: []("temp")
当然还有一些额外的行。
解决方案
该错误意味着您的地图是空的( results['current'] )请验证“results”是否不为空,如果不是,请验证是否有一个名为“current”的文件。
推荐阅读
- javascript - 当我使用 isAfter 方法比较 00:00:00 (24 小时格式)时,它返回 false
- javascript - react useEffect 无法识别对象更改(路由器历史记录)
- jmeter - 使用 JMeter 在线程之间分配负载
- uwp - WNS 中基于标签的广播通知
- javascript - 类型“CombinedVueInstance”上不存在属性“XXX”
>>' - php - PayPal 自动返回脚本总是被调用两次
- maven-3 - 如何加快 Maven 全新安装?耗时2小时完成
- python - PyMC3 在 Possion 模型创建期间产生错误
- python-3.x - 未定义符号:导入张量流时的_PyThreadState_Current
- thymeleaf - 使用 thymeleaf 从字符串中删除单引号字符