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 }';
   }
}
Share:
214
Bas van Dijk
Author by

Bas van Dijk

Updated on January 04, 2023

Comments

  • Bas van Dijk
    Bas van Dijk over 1 year

    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.

    • jamesdlin
      jamesdlin about 2 years
      Why do you think you need to do any explicit conversion? A List<MyLatLng> should already be substitutable for a List<LatLng>.
    • jamesdlin
      jamesdlin about 2 years
      There would be a problem if you passed the List<MyLatLng> to a function that tried to add a LatLng to it. If so, there are a number of ways to create a new List with the desired element type. List<T>.from(other list) would be a typical way.
    • GNassro
      GNassro about 2 years
      but if Lating does not have toJason method, why do you make it @override in MyLatLng ?
    • Bas van Dijk
      Bas van Dijk about 2 years
      @GNassro I realised that I shouldn't have done that
    • Bas van Dijk
      Bas van Dijk about 2 years
      @jamesdlin Thanks! Didn't knew about the .from method