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
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'],