简体   繁体   中英

type 'String' is not a subtype of type 'List<LatLng>' how do i convert the fallowing flutter string to LatLng for the use of Polygon

i am recoiving this data from API and i have to use as its, tried to split but then i get several errors //This data is string i would like to convert to it LatLng

var polypoints =
        "[LatLng(8.549726145655804, 47.30110634118318), LatLng(8.54721166008782, 47.301803715527065), LatLng(8.548983472319675, 47.30491507798434), LatLng(8.550479427132618, 47.30423916131258)]";
   // i have tried this i will get error 
    List<LatLng> latlngList = jsonDecode(polypoints);

   //Unhandled Exception: type 'String' is not a subtype of type 'List<LatLng>'

    List<LatLng> latlngList = jsonDecode(polypoints);
    var polygon = Polygon(
      points: polypoints,   //there is error here i have to use only LatLng
      strokeColor: Colors.red,
      strokeWidth: 2,
      fillColor: Colors.blue,
    );
    // i would like to be able to use as variable in the point below
    List<LatLng> pointst = [
      LatLng(8.549726145655804, 47.30110634118318),
      LatLng(8.54721166008782, 47.301803715527065),
      LatLng(8.548983472319675, 47.30491507798434),
      LatLng(8.550479427132618, 47.30423916131258)
    ];

     var polygoncorrect = Polygon(
      points: pointst,       //in here its same data but no i am hard coding it
      strokeColor: Colors.red,
      strokeWidth: 2,
      fillColor: Colors.blue,
    );

thank you

First, "[LatLng(8.549726145655804, 47.30110634118318), LatLng(8.54721166008782, 47.301803715527065) is no json.

It would need to look like { "LatLng": [ "Lat: 8.5", "Lng: 47.3" ] }

Then you would create a class for LatLng and create method to create the object:

class LatLng {
  float lat;
  float lng;
  LatLng(this.lat, this.lng);
  factory LatLng.fromJson(dynamic json) {
    return LatLng(json['lat'] as float, json['lng'] as float);
  }
  @override
  String toString() {
    return '{ ${this.lat}, ${this.lng} }';
  }
}

Haven't done anything in Flutter, lately, but this should more or less work. I quickly searched for similar issues, here, and adapted the code. Key words would be json decrypt nested array class

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM