Lesson 11 · 11 of 20
Sets · Dart
Use Dart sets to store values without repeats: remove duplicates with toSet() and compare hobbies with intersection, union and difference.

A set (Set) holds each value only once, and is written between braces: {'dart', 'flutter', 'mobile'}. Adding a value that is already there with add('dart') does nothing, which is why tags ends up with four tags and not five.
`toSet()` turns a list into a set and drops the repeats on the way: six visits are only three different cities. Dart sets keep the order in which each value first went in.
`contains()` is the typical question for a set, and it is very fast even with thousands of elements, because it does not go through the values one by one as a list does.
Two sets have the classic operations: `intersection()` gives what they share (what both Ana and Ben like), `union()` puts everything together without repeats and `difference()` gives what is only in the first. `remove()` takes a value out.
Watch out for empty braces: {} is an empty map (next lesson), not a set. An empty set needs its type, as in `<String>{}`.
Code · main.dart
void main() { // A set keeps each value only once, between { }. var tags = {'dart', 'flutter', 'mobile'}; tags.add('dart'); // already there: nothing changes tags.add('desktop'); print('Tags: $tags (${tags.length})'); // toSet() removes the repeated values of a list. var visits = ['Rome', 'Paris', 'Rome', 'Lisbon', 'Paris', 'Rome']; var cities = visits.toSet(); print('${visits.length} visits, ${cities.length} cities: $cities'); // contains is very quick in a set, even a big one. print('Been to Lisbon? ${cities.contains('Lisbon')}'); // Operations between two sets. var ana = {'chess', 'tennis', 'piano', 'cooking'}; var ben = {'tennis', 'football', 'cooking'}; print('Both like: ${ana.intersection(ben)}'); print('Either likes: ${ana.union(ben)}'); print('Only Ana: ${ana.difference(ben)}'); // remove takes a value out. ana.remove('piano'); print('Ana now: $ana'); // {} alone is an empty map: an empty set needs its type. var empty = <String>{}; print('Empty set: $empty, is empty? ${empty.isEmpty}');}Output · dart run main.dart
Tags: {dart, flutter, mobile, desktop} (4)
6 visits, 3 cities: {Rome, Paris, Lisbon}
Been to Lisbon? true
Both like: {tennis, cooking}
Either likes: {chess, tennis, piano, cooking, football}
Only Ana: {chess, piano}
Ana now: {chess, tennis, cooking}
Empty set: {}, is empty? trueKey points
- A
Setgoes between{ }and has no repeats. list.toSet()removes duplicates.contains()is very fast on a set.intersection,unionanddifferencecompare sets.- An empty set is written
<String>{}.
Exercise
Create two sets with the students signed up for music and for art, and print who goes to both, who goes only to music and how many different students there are in total.