Sub topic 4
Sets: Unique Elements and Set Operations
Prerequisites
Assume you know Dart variables, functions, loops, generics such as List<int>, and basic null safety. A set is a collection that stores each value at most once. Unlike a list, a set does not use positions as its main way to access data.
Use a set when membership matters: “Is this user subscribed?” or “Which tags appear in both groups?”
Creating and changing sets
A set literal uses braces:
void main() {
final colors = {'red', 'green', 'blue', 'red'};
print(colors); // {red, green, blue}
print(colors.length); // 3
colors.add('yellow');
colors.add('green'); // No duplicate is added.
colors.remove('red');
print(colors.contains('blue')); // true
print(colors); // {green, blue, yellow}
}The second 'red' disappears because sets reject duplicates. The add method returns true when it changes the set and false when the value already exists.
For an empty set, give Dart an explicit type:
final names = <String>{};
final numbers = Set<int>();The empty literal {} can be interpreted as a map in some contexts, so <String>{} makes your intention clear.
Set operations
Dart provides methods for common mathematical set operations. These methods return new sets. They do not change the original sets.
void main() {
final morning = {'tea', 'coffee', 'juice'};
final afternoon = {'coffee', 'water', 'juice'};
print(morning.union(afternoon));
// {tea, coffee, juice, water}
print(morning.intersection(afternoon));
// {coffee, juice}
print(morning.difference(afternoon));
// {tea}
print(afternoon.difference(morning));
// {water}
}| Operation | Meaning | Example result |
|---|---|---|
| `union` | Values in either set | `{tea, coffee, juice, water}` |
| `intersection` | Values in both sets | `{coffee, juice}` |
| `difference` | Values in the first set but not the second | `{tea}` |
You can also remove all values shared with another set by using difference and assigning the result:
final allowed = {'read', 'write', 'delete'};
final requested = {'read', 'delete'};
final denied = requested.difference(allowed);
print(denied); // {}Iterating over a set
Use for-in to visit each value:
void main() {
final tags = {'dart', 'flutter', 'mobile'};
for (final tag in tags) {
print(tag);
}
}A set is an Iterable, so it also supports methods such as where, map, and toList. For example:
void main() {
final scores = {42, 75, 88, 91};
final passing = scores.where((score) => score >= 60).toSet();
print(passing); // {75, 88, 91}
}The call to toSet() keeps the transformed result as a set. Without it, where returns an Iterable<int>.
Visual model
Exercise
Which operation returns values present in first but absent from second?
Show answer
first.difference(second).