Reputation: 401
I am still learning flutter and I came throuygh a very weird error and still not getting why I have it. Here is my file
class _LocationScreenState extends State<LocationScreen> {
WeatherModel weather = WeatherModel();
int temperature;
String weatherIcon;
String cityName;
String weatherMessage;
@override
void initState() {
super.initState();
updateUI(widget.locationWeather);
}
void updateUI(dynamic weatherData) {
setState(() {
if (weatherData == null) {
temperature = 0;
weatherIcon = 'Error';
weatherMessage = 'Unable to get weather data';
cityName = '';
return;
}
double temp = weatherData['main']['temp'];
temperature = temp.toInt();
var condition = weatherData['weather'][0]['id'];
weatherIcon = weather.getWeatherIcon(condition);
weatherMessage = weather.getMessage(temperature);
cityName = weatherData['name'];
});
}
The error is
type int is not a subtype of type double
I would like to understand why I am getting this error.
Upvotes: 1
Views: 620
Reputation: 5005
This error happens when you try to pass a value of type int
into a variable of type double
.
Dart does not automatically cast those types you have to handle it manually. So you have two options here:
num
wich will cast the value automatically to double
because both int
and double
extends from num
.num temperature;
temperature = 24; // works
temperature = 24.5; // also works
num
. Works because num
is the super class of double
.int temperature;
temperature = 24.0 as num; // works
// does not work
// temperature = 24.5 as int;
Upvotes: 0
Reputation: 1227
As the error says
type 'int' is not a subtype of type 'double'
that's because you're storing a data of type int in a variable of type double so try this code
double temp = weatherData['main']['temp'].toDouble();
Upvotes: 2