Json to widget : what is the right type for nested object?

Hello, I’m trying to generate some widget based on my returned JSON that I call from an API.

But can’t find a way to make this work, I can’t find the right type to assign to my variable I guess…

for the model, I tried Map, dynamic, List… but always a different error du to the type of the field when I try to do the foreach…

/* MODEL */
class Preference {
  final int id;
  final Map lieux;
  final Map thematiques;

  Preference(
  {this.id,
  this.lieux,
  this.thematiques,});

  factory Preference.fromJson(Map<String, dynamic> json) {
var pref = Preference(
  id: json["id"],
  lieux: json["lieux"],
  thematiques: json['thematiques'],
);
return pref;
  }
}

/* JSON return */
{
"id": 5506,
"lieux": {
    "1": {
        "cle": "1",
        "ville": "city"
    },
    "2": {
        "cle": "2",
        "ville": "city 2"
    }
},
"thematiques": {
    "1": {
        "cle": "1",
        "theme": "Culture"
    }
},
}

/* Factory */
Future<Preference> getPreferences() async {
  var userId = Globals.userId;

  var headers = Constants.headers;

  var query = Constants.pref + '?id=$userId';
  var uriResponse = await client.get(query, headers: headers);
  var bodyResponse = uriResponse.body;
  var pref = Preference.fromJson(json.decode(bodyResponse));

  return pref;
}

/* Widget */
  @override
  void initState() {
super.initState();

var data = PreferenceController().getPreferences();
data.then((preference) {
  pref = preference;
  var lieux = pref.lieux;
  lieux.forEach((lieu){
    generateStuff();
  });
});

Go it : I’ve created object instead of array of data in my API

then I converted the result of the API call thanks to this awesome website :

Json to DART

3 Likes