首页 > 解决方案 > 在 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")

当然还有一些额外的行。

标签: jsonflutterweatheropenweathermapweather-api

解决方案


该错误意味着您的地图是空的( results['current'] )请验证“results”是否不为空,如果不是,请验证是否有一个名为“current”的文件。


推荐阅读