Home > Blockchain >  The method '[]' was called on null. Receiver: null Tried calling: []("icon")
The method '[]' was called on null. Receiver: null Tried calling: []("icon")

Time:08-06

I'm trying to solve this problem by changing the code in every way. But don't understand exactly what's the problem here. No matter how i'm changing the code this error is coming at the end. And it shows that my problem in the FutureBuilder .Please, try to help me.

Also check my api please. {"coord":{"lon":90.4167,"lat":24.1667},"weather":[{"id":500,"main":"Rain","description":"light rain","icon":"10d"}]

  Widget updateTempWidget(String city) {
return FutureBuilder(
    future: getWheather(util.appID, city),
    builder: (BuildContext context, AsyncSnapshot snapshot) {
      if (snapshot.hasData) {
        Map content = snapshot.data!;
        return Container(
          child: Column(
            children: [
              ListTile(
                title: Text(content["weather"]["icon"].toString()),
              )
            ],
          ),
        );
      }
      if (snapshot.hasError) {
        return Text("Error");
      }
      return CircularProgressIndicator();
    });

} }

CodePudding user response:

First of all you should try putting some print statements (or better use debugger) near the line where you retrieve the data.

if (snapshot.hasData) {
        Map content = snapshot.data!;
        print(content);

Check the object which you are getting and verify that the icon coming from the api is not null. It will also show you the structure of the data. You can also directly try logging icon to console

CodePudding user response:

Note that weather is a list and not a map and be careful when using nullable operators, I recommend always mapping the objects from an api to a class checking each object and avoiding using null variables, try to use default values like empty list, empty string, etc.

  Widget updateTempWidget(String city) {
    return FutureBuilder(
        future: getWheather(util.appID, city),
        builder: (BuildContext context, AsyncSnapshot snapshot) {
          if (snapshot.hasData) {
            var content = snapshot.data ?? {};
            var _weather = content['weather'];
            if(_weather is List){
              var _icon =_weather.isNotEmpty ? (_weather[0]['icon'] ?? 'undefined' ): 'list is empty';
              return Container(
                child: Column(
                  children: [
                    ListTile(
                      title: Text(_icon),
                    )
                  ],
                ),
              );
            }
            return Text("Weather is not list");

          }
          if (snapshot.hasError) {
            return Text("Error");
          }
          return CircularProgressIndicator();
        });
  }
  • Related