Karel Debedts
Karel Debedts

Reputation: 5768

Specific elements of map to list in dart (flutter)

I have a List with multiple Maps in dart:

[{name: name1, id: 1259}, {name: name2, id: 2333}]

I would like to end up with a List that contains all the ids, like this.

[1259,2333, ... ]

How can I do that?

Upvotes: 0

Views: 342

Answers (1)

CopsOnRoad
CopsOnRoad

Reputation: 267404

Try this:

var data =  [{"name": "name1", "id": 1}, {"name": "name2", "id": 2}];
var list = [];
for (var item in data) {
  list.add(item["id"]);
}  

print("$list"); // [1, 2]

Edit:

You can directly use this (as suggested by Eugene)

var list = data.map((item) => item["id"]).toList();
list.forEach(print); // [1, 2]

Upvotes: 1

Related Questions