A Set in Dart is an unordered collection of unique items. Unlike Lists, Sets do not allow duplicate values, and the order of elements is not guaranteed. They are incredibly useful for ensuring data integrity (e.g., a list of unique email addresses).
1. Declaring Sets
Sets are written using curly braces {}. However, because Maps also use curly braces, you must be careful when declaring an empty Set.
Creating Sets
1// 1. Literal syntax2var fruits = {'apple', 'banana', 'orange'};3 4// 2. Explicit type5Set<int> numbers = {1, 2, 3};6 7// 3. The "Empty Set" Gotcha8// var empty = {}; // ⚠️ This creates a Map, NOT a Set!9 10// ✅ Correct ways to create an empty Set:11var emptySet1 = <String>{};12Set<String> emptySet2 = {};HintDart assumes {} is a Map by default. To create an empty Set, you must provide type arguments (like <String>) or specify the variable type.
2. Uniqueness (No Duplicates)
The defining feature of a Set is that it automatically ignores duplicate entries. If you try to add an item that already exists, the Set remains unchanged.
Handling Duplicates
1var colors = {'red', 'green', 'blue'};2 3// Try adding 'red' again4colors.add('red');5colors.add('red');6 7print(colors); // Output: {red, green, blue}8print(colors.length); // Output: 39 10// Adding a new item11colors.add('yellow'); // Output: {red, green, blue, yellow}HintThis feature makes Sets perfect for tasks like removing duplicates from a List (e.g., myList.toSet().toList()).
3. Common Set Methods
Sets provide efficient methods for checking if an item exists and for modifying the collection.
Using Set Methods
1Set<String> students = {'Alice', 'Bob', 'Charlie'};2 3// Check if item exists (Fast operation)4print(students.contains('Alice')); // true5print(students.contains('Dave')); // false6 7// Add and Remove8students.add('Dave');9students.remove('Bob');10 11print(students); // {Alice, Charlie, Dave}12 13// Set Operations (Intersection, Union)14var setA = {1, 2, 3};15var setB = {3, 4, 5};16 17print(setA.intersection(setB)); // {3} (Items in both)18print(setA.union(setB)); // {1, 2, 3, 4, 5} (Combined unique)HintSets are optimized for checking contains, making them faster than Lists for large collections when checking for existence.
Loot collected
Key takeaways- Sets are unordered collections of unique elements.
- Duplicates are automatically ignored when adding to a Set.
- Use
<Type>{}orSet<Type> = {}to create an empty Set (avoidvar x = {}). - Sets are faster than Lists for checking if an item exists (
contains). - You can easily convert between Lists and Sets using
.toSet()and.toList().
Side quests
Practice exercises
Exercise 1: Unique Guests
Create a Set called guests. Add "Mario" twice and "Luigi" once. Print the length of the set.
Reveal solutionHide solution
1var guests = {'Mario', 'Luigi'}; guests.add('Mario'); print(guests.length); // Output: 2Exercise 2: List to Set
Given a list [1, 2, 2, 3, 4, 4], convert it to a Set to remove duplicates.
Reveal solutionHide solution
1var numbers = [1, 2, 2, 3, 4, 4]; var uniqueNumbers = numbers.toSet(); print(uniqueNumbers);Exercise 3: Empty Set Declaration
Declare an empty Set of Strings correctly.
Reveal solutionHide solution
1var names = <String>{}; // OR Set<String> names = {};