Json 方法';[]和#x27;在空颤振时被调用
我想从api访问天气数据。json是这样的: 我的代码的相关部分如下:Json 方法';[]和#x27;在空颤振时被调用,json,flutter,weather,openweathermap,weather-api,Json,Flutter,Weather,Openweathermap,Weather Api,我想从api访问天气数据。json是这样的: 我的代码的相关部分如下: 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 re
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'的字段。问题在这一行
this.temp=results['current']['temp']代码>
results['current']
将返回null作为响应,您稍后也将尝试使用temp
访问它
因为结果['current']
为空。您正在尝试类似的操作:null['temp']
解决方案是检查current
键是否有值,如果有,则访问temp
键值。可能是结果
为空,您没有访问internet等的权限。但这是其他问题的材料,正如您在这里所问的那样,您为什么得到方法“[]”是在null上调用的-颤振
您测试了端点吗?你确定你得到了正确的回答吗?如果没有,请使用类似Postman的工具测试端点,或在“调试工具”的“网络”选项卡中检查响应端点的内容。@Julianzapa是。我测试了结果['lat'],结果是确定的,这就是您使用的确切URL吗?如果是,则您没有在URL末尾替换apikey。URL需要一个有效的api键才能返回结果。@bluenile否我使用了我的api键,但在发布问题时对其进行了编辑。您能否发布收到的确切答复。对不起,我上载了错误的图像。现在我用正确的截图编辑了链接