Reputation: 984
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
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
Reputation: 6524
Other than doing what @Patrick suggested, you also have to major ways:
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"}
]
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