Home > Back-end >  Dart parsing nested array to data class
Dart parsing nested array to data class

Time:08-18

Below output sample returning by the server which i should use Dart classes to create data class from them

const cities = """[
  {
    "id": 1,
    "province_id": 1,
    "name": "test1",
    "neighborhood": []
  },
  {
    "id": 2,
    "province_id": 1,
    "name": "test2",
    "neighborhood": [
      {"id": 1, "city_id": 1, "name": "xxx 1"},
      {"id": 2, "city_id": 1, "name": "xxx 2"}
    ]
  }
]
""";

as you can see cities is an Array and into that neighborhood is as array too

data class which i implemented for them:

@freezed
class City with _$City {
  const factory City(
    final int id,
    @JsonKey(name: 'province_id') final int provinceId,
    final String name,
    final List<Neighborhood>? neighborhood,
  ) = _City;

  factory City.fromJson(Map<String, dynamic> json) => _$CityFromJson(json);
}

@freezed
class Neighborhood with _$Neighborhood {
  const factory Neighborhood(
    final int id,
    @JsonKey(name: 'city_id') final int cityId,
    final String name,
  ) = _Neighborhood;

  factory Neighborhood.fromJson(Map<String, dynamic> json) => _$NeighborhoodFromJson(json);
}

and now when i try to use this code to convert json data i get error:

final List<Map<String,dynamic>> data = json.decode(cities) as List<Map<String,dynamic>>;
final city = data.map((elements) => City.fromJson(elements)).toList();

Error:

The argument type 'Map<String, dynamic> Function(dynamic)' can't be assigned to the parameter type 'Iterable<dynamic>'.

CodePudding user response:

You should be mapping the result like

final l = json.decode(cities);
List<City> city = l.map((elements) => City.fromJson(elements)).toList();
  • Related