William
William

Reputation: 984

Create unique set of maps in Dart

I need to create a unique set of maps but it seems that adding maps to a set doesn't filter and adds duplicates.

Set mySet = Set();

List myList = [
  {"name": "Jane"},
  {"name": "Jane"},
  {"name": "Mary"}
]

for(var item in myList){
  mySet.add(item);
}

Doing this causes the set to contain all three maps. Is there any way to only have one Jane?

Upvotes: 0

Views: 2065

Answers (2)

Patrick
Patrick

Reputation: 3759

This is because the Maps are different: {"name": "Jane"} != {"name": "Jane"}.

You have to create your own class and override == (and hashCode).

See "Implementing map keys": https://dart.dev/guides/libraries/library-tour

Upvotes: 2

Mattia
Mattia

Reputation: 6524

Other than doing what @Patrick suggested, you also have to major ways:

  1. If your map is constant just declare it as a const so they will reference always the same object, hence the Set will work as you expect to:
List myList = const [
  {"name": "Jane"},
  {"name": "Jane"},
  {"name": "Mary"}
]
  1. Check if a map with the same name already exists before adding the new one:
  for(var item in list){
    // If a map with the same name exists don't add the item.
    if (set.any((e) => e['name'] == item['name'])) {
      continue;
    }
    set.add(item);
  }

Just a quick note, you can initialize a Set using its literal constructor (there is a linter rule about this):

var set = <Map<String, String>>{}

Upvotes: 2

Related Questions