Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

snapshot.hasData returning false even though response.body has data [Flutter]

I am trying to get current weather info from OpenWeather and display the result in Text Widget after checking that there is data returned. However, that condtion (snapshot.hasData) is always returned as false and else condition (CircularProgressIndicator) is invoked.
Here is the FutureBuilder.

class WeatherPage extends StatefulWidget {
  @override
  State<WeatherPage> createState() => _WeatherPageState();
}

class _WeatherPageState extends State<WeatherPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: FutureBuilder(
          future: getCurrentWeather(),
          builder: (context, snapshot) {
            if (snapshot.hasData) {
              WeatherModelCurrent weather =
                  snapshot.data as WeatherModelCurrent;

              return weatherBox(weather);
            } else {
              return const CircularProgressIndicator();
            }
          },
        ),
      ),
    );
  }

here is the getCurrentWeather() function

Future getCurrentWeather() async {
    WeatherModelCurrent? weather;

    var url = Uri.parse(
        "https://api.openweathermap.org/data/2.5/weather?q=Kathmandu&appid=82c7b99e2a8215351147f607592a3e63&units=metric");
    var response = await http.get(url);
//response.body has the data returned by API call
    print(response.body);

    if (response.statusCode == 200) {
      weather = WeatherModelCurrent.frommJson(jsonDecode(response.body));
    
    } else {
      print('error');
    }

    return weather;
  }

and here is the model class

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

class WeatherModelCurrent {
  double temp;
  double feelslike;
  double tempmin;
  double tempmax;
  String description;

  WeatherModelCurrent(
      {required this.temp,
      required this.feelslike,
      required this.tempmin,
      required this.tempmax,
      required this.description});

  factory WeatherModelCurrent.frommJson(Map<String, dynamic> jsonn) {
    return WeatherModelCurrent(
      temp: jsonn['main']['temp'].toDouble(),
      feelslike: jsonn['main']['feels_like'].toDouble(),
      tempmin: jsonn['main']['temp_min'].toDouble(),
      tempmax: jsonn['main']['temp_max'].toDouble(),
      description: jsonn['weather']['description'],
    );
  }
}

>Solution :

Try & catch your getCurrentWeather code block, we can get the following exception:

flutter: exception type 'String' is not a subtype of type 'int' of 'index'

The response json is like:

{
    "weather":[
        {
            "id":803,
            "main":"Clouds",
            "description":"broken clouds",
            "icon":"04d"
        }
    ],
}

Your code description: jsonn['weather']['description'] should be description: jsonn['weather'][0]['description'],

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading