-1

I want to access weather data from api. the json is this: jsoncode

and the relevant part of my code is like this:

  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'];
    });
  }

and this is the error i get:

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")

and some extra lines of course.

  • Did you test the endpoint? Are you sure you are getting the correct response? If not, then test your endpoint with something like Postman or check in the debugger tools the network tab to check what is responding the endpoint. – julian zapata Dec 08 '20 at 18:27
  • @julianzapata yes. I tested results['lat'] and it was ok – Mahdi Aghajani Dec 08 '20 at 18:29
  • Is this the exact URL you are using? http://api.openweathermap.org/data/2.5/onecall?lat=$lat&lon=$long&exclude=alerts&appid=apikey If YES then you did not replace your apikey at the end of the URL. The URL needs a valid apikey to return results. – bluenile Dec 08 '20 at 18:38
  • @bluenile no i used my api key but edited it when posting the question. – Mahdi Aghajani Dec 08 '20 at 18:41
  • Can you post the exact response you receive. – bluenile Dec 08 '20 at 18:42

2 Answers2

0

The error means that your map is Empty ( results['current'] ) please verify if 'results' is not null, if it's not than verify that there is a filed named 'current'.

Oussama Belabbas
  • 196
  • 1
  • 10
0

the issue is in this line this.temp = results['current']['temp'];

results['current'] is returning you null as response and you are trying to access it later with temp also.

Because results['current'] is null. You are trying something similar to this: null['temp'].

The solution would be to check if there is a value for current key, if there is, then access to temp key value. It can be that results is null, that you don't have permissions for internet etc. but that's material for other question, as you asked here why are you getting The method '[]' was called on null - Flutter

Nihad Delic
  • 220
  • 2
  • 11