Home > Net >  Convert/cast class to parent class type
Convert/cast class to parent class type

Time:03-27

Flutter mapbox_gl has a LatLng class which does not have a toJson() and fromJson() method. Therefore I've inherited this class to my own class and added the methods

class 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 and MyLatLng are exactly the same only MyLatLng have the json methods implemented.

CodePudding user response:

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 }';
   }
}
  • Related