mirkancal
mirkancal

Reputation: 5385

How to convert List of Objects to Map and use the object's property as key?

I have list of coin objects, I want to cast the list to the map. How can I use id's as a Map key?

class Coin {
  int id;
  String groupID;
  String symbol;
  int coinOrder;
  String fullName;
}

Upvotes: 2

Views: 1653

Answers (2)

Ryan Heitner
Ryan Heitner

Reputation: 13652

For Flutter 3 >

final Map<int, Coin> coinMap = {
  for (var coin in coins)
    coin.id: coin
};

Upvotes: 0

Gunhan
Gunhan

Reputation: 7045

There is a fromIterable constructor for Map class. You can use it to convert a list to a map.

Map<int, Coin> map = Map.fromIterable(list, key: (item) => item.id, value: (item) => item);

Upvotes: 4

Related Questions