flutteroopobject-object-mapping

How to add value from Json into a list object using Flutter?


I have a class User and a List like this:

List<User> users = List();

class User {
  int id;
  String name;

  User({this.id, this.name});

  factory User.fromJson(Map<String, dynamic> json) {
    return User(
      id: json["id"] as int,
      name: json["name"] as String
    );
  }
}

and a Json Data like below:

  var DataUser= [
    {"id": 1, "name": "Leanne"},
    {"id": 2, "name": "Graham"}
  ];

How can I add value from DataUser into List<User> users?


Solution

  • You can iterate through the List of json objects and use your User.fromJson to convert each json object to a User object.

    I added a demo using your code as an example:

    List<User> users = List();
    
      var DataUser = [
        {"id": 1, "name": "Leanne"},
        {"id": 2, "name": "Graham"}
      ];
    
      List<User> getUsersFromJson() {
        // iterate through the list of json
        for (var json in DataUser) 
        // add the user object to your list
        users.add(User.fromJson(json));
        // return the list of users
        return users;
      }