What is a Set?
A Set is an unordered collection of unique values. Duplicate items are automatically ignored. Sets are ideal when you need uniqueness or fast membership checks.
Creating Sets
Set<int> primes = {2, 3, 5, 7, 11};
Set<String> colors = {'red', 'green', 'blue'};
// Adding a duplicate — silently ignored
colors.add('red');
print(colors.length); // 3 (still)
// Empty set — must use Set(), not {} (that creates a Map)
var empty = <String>{}; // or: Set<String>()
// From list (removes duplicates)
var nums = [1, 2, 2, 3, 3, 3];
var unique = nums.toSet(); // {1, 2, 3}
Set Operations
var a = {1, 2, 3, 4, 5};
var b = {3, 4, 5, 6, 7};
// Union — all elements from both
print(a.union(b)); // {1, 2, 3, 4, 5, 6, 7}
// Intersection — elements in both
print(a.intersection(b)); // {3, 4, 5}
// Difference — in a but not b
print(a.difference(b)); // {1, 2}
Example
void main() {
Set<String> enrolled = {'Alice', 'Bob', 'Carol', 'Dave'};
Set<String> paid = {'Bob', 'Carol', 'Eve'};
// Who enrolled AND paid?
var confirmed = enrolled.intersection(paid);
print('Confirmed: $confirmed'); // {Bob, Carol}
// Who enrolled but NOT paid?
var unpaid = enrolled.difference(paid);
print('Unpaid: $unpaid'); // {Alice, Dave}
// Everyone involved
var all = enrolled.union(paid);
print('All: $all'); // {Alice, Bob, Carol, Dave, Eve}
// Membership check — O(1)
print(enrolled.contains('Alice')); // true
}
Output:Confirmed: {Bob, Carol}
Unpaid: {Alice, Dave}
All: {Alice, Bob, Carol, Dave, Eve}
true
🧠 Quiz
1. What happens when you add a duplicate to a Set?
- A) Error is thrown
- B) It is silently ignored ✅
- C) The old value is replaced
- D) A second copy is added
2. How do you create an empty Set in Dart?
- A) {}
- B) []
- C) <String>{} ✅
- D) Set()
Summary
Sets are unordered collections of unique values. Duplicates are ignored. Key operations: union(), intersection(), difference(). Membership checks are O(1). Use <Type>{} to create an empty set (not {} which creates a Map).