Dart Sets
A Set<E> is an unordered collection of unique elements. Adding a value that's already present does nothing. Sets are ideal for membership tests ("have I seen this?"), removing duplicates and set algebra like union and intersection.
Creating sets
void main() {
var tags = {'dart', 'flutter', 'dart', 'mobile'}; // duplicate ignored
var empty = <String>{}; // typed empty set
var notASet = {}; // careful: this is an empty Map!
var fromList = Set.of([3, 1, 3, 2, 1]);
const vowels = {'a', 'e', 'i', 'o', 'u'};
print(tags);
print(tags.length);
print(empty.runtimeType);
print(notASet is Map);
print(fromList);
print(vowels.contains('e'));
}{dart, flutter, mobile}
3
_Set<String>
true
{3, 1, 2}
true
Note:
{}alone is an empty map, because maps came first. Write<String>{}orSet<String>()for an empty set.
The default Set implementation is a LinkedHashSet, which remembers insertion order — so iteration order is predictable even though sets are conceptually unordered.
Adding, removing and checking
void main() {
var visited = <String>{};
for (final page in ['home', 'shop', 'home', 'cart', 'shop']) {
if (visited.add(page)) {
print('first visit: $page');
} else {
print('already seen: $page');
}
}
print(visited);
visited.remove('shop');
print(visited.contains('shop'));
print(visited.containsAll(['home', 'cart']));
}first visit: home
first visit: shop
already seen: home
first visit: cart
already seen: shop
{home, shop, cart}
false
true
add returns true when the element was new — a neat way to detect duplicates in a single step.
Set algebra
| Method | Result |
|---|---|
a.union(b) |
Everything in a or b |
a.intersection(b) |
Only what's in both |
a.difference(b) |
In a but not in b |
a.containsAll(b) |
Is b a subset of a? |
void main() {
var lan = {'python', 'dart', 'sql'};
var minh = {'dart', 'go', 'sql', 'rust'};
print('Both know: ${lan.intersection(minh)}');
print('Together: ${lan.union(minh)}');
print('Only Lan: ${lan.difference(minh)}');
print('Only Minh: ${minh.difference(lan)}');
var symmetric = lan.union(minh).difference(lan.intersection(minh));
print('Exactly one: $symmetric');
}Both know: {dart, sql}
Together: {python, dart, sql, go, rust}
Only Lan: {python}
Only Minh: {go, rust}
Exactly one: {python, go, rust}
Removing duplicates while keeping order
Converting a list to a set and back is the idiomatic way to deduplicate:
void main() {
var emails = ['a@x.com', 'b@x.com', 'a@x.com', 'c@x.com', 'b@x.com'];
var unique = emails.toSet().toList();
print(unique);
// case-insensitive dedupe: remember normalised keys
var names = ['Lan', 'lan', 'Hung', 'LAN', 'hung'];
var seen = <String>{};
var firstSpellings = names.where((n) => seen.add(n.toLowerCase())).toList();
print(firstSpellings);
}[a@x.com, b@x.com, c@x.com]
[Lan, Hung]
Sets and equality
Sets use == and hashCode to decide whether two elements are the same. Built-in types (numbers, strings, records, enums) already implement these correctly. For your own classes, override both — otherwise two "equal" objects are treated as different:
class Tag {
final String name;
const Tag(this.name);
@override
bool operator ==(Object other) => other is Tag && other.name == name;
@override
int get hashCode => name.hashCode;
}
void main() {
var tags = {Tag('new'), Tag('sale'), Tag('new')};
print(tags.length);
var points = {(1, 2), (1, 2), (2, 1)}; // records have value equality
print(points);
}2
{(1, 2), (2, 1)}
Tip: Need sorted iteration? Use
SplayTreeSetfromdart:collection, which keeps elements ordered by a comparator.
Lookup speed
| Operation | List |
Set (hash-based) |
|---|---|---|
contains(x) |
O(n) — scans every element | O(1) on average |
| Keeps duplicates | Yes | No |
Index access [i] |
Yes | No |
If you check membership frequently in a large collection, a Set is dramatically faster than a List.
Test yourself
What is the type of var x = {};?
- Set<dynamic>
- Map<dynamic, dynamic>
- List<dynamic>
- Compile error
What does set.add(x) return when x is already in the set?
- true
- false
- null
- It throws
Which method gives the elements present in both sets?
- union
- difference
- intersection
- merge