Home > front end >  How can I add list element in Map<String, dynamic>
How can I add list element in Map<String, dynamic>

Time:10-22

Now I have the classes like below:

class A {
    String? name;
    List<Friend> friends = [];

    A(this.name, this.friends);
}


class Friend {
    String? name;
    int? age;

    Map<String, dynamic> toMap() {
        return {
            "name" : this.name,
            "age" : this.age
        };
    }

    Friend(this.name, this.age);
}

And I want to make Map which has friends list. Like below:

{
    "name" : name,
    "friends" : [for(var f in frirnds) f.toMap()]
}

However, this map has only one element in friends list. It is inpossible to write each elements like below because the list length is not static.

{
    "name" : name,
    "friends" : [friends[0].toMap(), friends[1].toMap(), friends[2].toMap(), ... ]
}

What should I do if I want to add all elements of list in map?

CodePudding user response:

you can use map method on Iterable and convert it to list like this:

{
    "name" : name,
    "friends" : friends.map((e) => e.toMap()).toList()
}
  • Related