Parsing double values from JSON in Flutter and Dart
Solution 1
The Dart JSON parser converts the property inside json and apparently is clever enough to spit a double type.
someVariable as double
expects a String at the left side.
Whats probably happening is that you're trying to convert a double into a double.
I would try something like this:
lat: json["lat"].toDouble(),
This would cover the case of the data in your JSON comes like "5". In this case the dart json converter would cast the type to int and it would break your code if you are always expecting a double.
Solution 2
I was having the same problem, the way I think it was this:
class MapPoint {
String title;
double lat;
double lng;
MapPoint({this.title, this.lat, this.lng});
factory MapPoint.fromJson(Map<String, dynamic> json) {
return MapPoint(
title: json["title"] as String,
lat: json["lat"] is int ? (json['lat'] as int).toDouble() : json['lat'],
lng: json["lng"] is int ? (json['lng'] as int).toDouble() : json['lng']
);
}
}
Solution 3
I can not reproduce
void main() {
final json = {
"point": {"title": "Point title", "lat": 42.123456, "lng": 32.26567}
};
final p = MapPoint.fromJson(json);
print(p);
}
class MapPoint {
String title;
double lat;
double lng;
MapPoint({this.title, this.lat, this.lng});
factory MapPoint.fromJson(Map<String, dynamic> json) {
return MapPoint(
title: json["title"] as String,
lat: json["lat"] as double,
lng: json["lng"] as double);
}
}
Solution 4
i can fix this problem this way
class MapPoint {
String title;
double lat;
double lng;
MapPoint({this.title, this.lat, this.lng});
factory MapPoint.fromJson(Map<String, dynamic> json) {
return MapPoint(
title: json["title"] as String,
lat: json["lat"] *1.0,
lng: json["lng"] *1.0
);
}
}
Comments
-
moonvader about 2 years
I have problems while I try to get double values from JSON in Flutter.
class MapPoint { String title; double lat; double lng; MapPoint({this.title, this.lat, this.lng}); factory MapPoint.fromJson(Map<String, dynamic> json) { return MapPoint( title: json["title"] as String, lat: json["lat"] as double, lng: json["lng"] as double ); } }
For some reason I got error
Dart Error: Unhandled exception: type 'double' is not a subtype of type 'String'
I tried some to user
double.parse(json["lng"])
instead but got same error.
Same time this way of getting data from JSON works fine with other types.This is JSON example
{ point: { title: "Point title", lat: 42.123456, lng: 32.26567 } }
-
Hedron Dantas about 4 yearslat: double.parse(json["lat"])
-
Sisir over 3 yearsIf you are not sure whethe rthe type is int or double; better to declare it as
num