1

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?

1 Answer 1

2

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;
  }

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.