Set
- Dart course
- Beginner
- Lesson 59/116
- 5 min
Learn unique collections with Set.
The Set collection
A Set in Dart is a collection of unique elements. If you add the same value twice, the second one is ignored; the Set enforces the 'each element appears once' rule for you.
You create a Set with the {a, b, c} literal or the Set<T> type. For example {'a', 'b', 'a'} becomes {a, b}; the duplicate 'a' is dropped automatically.
Unlike a list, a Set does not index its elements; it answers 'does it contain x?' quickly with contains. Use a Set whenever duplicates must be prevented.
Creating a Set
You can declare an empty Set in two ways. The first is the explicit type: Set<String> fruits = {};. The second is the typed literal: var fruits = <String>{};. Both mean the same thing.
When you pre-fill it, the literal is concise: var fruits = <String>{'apple', 'pear'};. The <String> prefix tells Dart the curly braces are a Set, not a Map.
If you write a bare {}, Dart may read it as an empty Map; for an empty Set, always use <T>{} or Set<T>.
Practice Print three fruits
Create a Set<String>, add three fruits to it and print it with print. Use three distinct fruits.
Starter code
void main() {
// Create a Set and add three fruits
// print
}Sample solution
void main() {
Set<String> fruits = {'apple', 'pear', 'cherry'};
print(fruits);
}Expected output
{apple, pear, cherry}
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which is a Set property?
- Duplicate elements
- Unique elements Correct answer
- Fixed size
- Indexed access
Explanation: a Set keeps each value only once.
2 Define a Set
void main() {
var fruits = ____;
print(fruits);
}
void main() {
var fruits = <String>{'apple', 'pear'};
print(fruits);
}
Explanation: the <String>{} prefix marks this as a Set.
3 Match the Set parts
| Term | Meaning |
|---|---|
Set<String> |
Set of strings type |
<String>{} |
Empty Set literal |
{a, b} |
Two-element Set literal |
contains |
Membership test |