Convert/cast class to parent class type
214
Solution ^^
convert() {
var data = [
{"latitude":"23432324234","longitude":"21321324321"},
{"latitude":"23432324234","longitude":"21321324321"},
{"latitude":"23432324234","longitude":"21321324321"},
{"latitude":"23432324234","longitude":"21321324321"},
];
List<LatLng> latLng=MyLatLng.toArray(data);
}
-------
class MyLatLng extends LatLng {
MyLatLng(double latitude, double longitude) : super(latitude,
longitude);
******
static List<LatLng> toArray(dynamic data){
return data.map<LatLng>((e) {return MyLatLng.fromJson(e);}).toList();
}
@override
String toString() {
return 'MyLatLng{ $latitude;$longitude }';
}
}
Author by
Bas van Dijk
Updated on January 04, 2023Comments
-
Bas van Dijk over 1 year
Flutter mapbox_gl has a
LatLng
class which does not have atoJson()
andfromJson()
method. Therefore I've inherited this class to my own class and added the methodsclass MyLatLng extends LatLng { MyLatLng(double latitude, double longitude) : super(latitude, longitude); @override Map<String, dynamic> toJson() { return { 'latitude': latitude, 'longitude': longitude, }; } @override factory MyLatLng.fromJson(Map<String, dynamic> json) { double _latitude = double.parse(json['latitude']); double _longitude = double.parse(json['longitude']); return MyLatLng(_latitude, _longitude); } }
I have a list
var latLngList = <MyLatLng>[];
How can I convert this list to a list with the type<LatLng>[]
?LatLng
andMyLatLng
are exactly the same onlyMyLatLng
have the json methods implemented.-
jamesdlin about 2 yearsWhy do you think you need to do any explicit conversion? A
List<MyLatLng>
should already be substitutable for aList<LatLng>
. -
jamesdlin about 2 yearsThere would be a problem if you passed the
List<MyLatLng>
to a function that tried to add aLatLng
to it. If so, there are a number of ways to create a newList
with the desired element type.List<T>.from(other list)
would be a typical way. -
GNassro about 2 yearsbut if Lating does not have
toJason
method, why do you make it@override
inMyLatLng
? -
Bas van Dijk about 2 years@GNassro I realised that I shouldn't have done that
-
Bas van Dijk about 2 years@jamesdlin Thanks! Didn't knew about the .from method
-