Search code examples
jsonflutterflutterflow

Convert Json to Custom Data Type List in Dart


I am trying to parse my REST API output in Flutterflow with a custom flutter function. My JSON looks like this:

{
  "markers": [
    {
      "entityId": 123
      "lat": 10.32,
      "lng": 9.32
    },
    {
      "entityId": 124
      "lat": 11.32,
      "lng": 8.32
    }
  ],
  "config": ...
}

And my custom function in Flutter looks like this:

List<MapLocationStruct>? createLocationsFromJson(dynamic jsonMarkers) {
  /// MODIFY CODE ONLY BELOW THIS LINE

  List<MapLocationStruct> locations = [];
  dynamic markers = jsonDecode(jsonMarkers['markers']);
  markers.forEach((element) {
    MapLocationStruct location = new MapLocationStruct(
        entityId: element['entity_id'],
        latLng: new LatLng(element['lat'], element['ng']));
    locations.add(location);
  });
  return locations;

  /// MODIFY CODE ONLY ABOVE THIS LINE
}

No matter what I try, I always get errors, when I test the function. How can I parse the json correctly in flutter(flow)?


Solution

  • if jsonMarkers is the JSON string you shouldn't do

    dynamic markers = jsonDecode(jsonMarkers['markers']);
    

    but

    dynamic markers = jsonDecode(jsonMarkers)['markers'];
    

    but jsonMarkers being dynamic probably means that it already is decoded, so you could do

    dynamic markers = jsonMarkers['markers'];