Sets in Dart
In this lesson, you will learn about Sets in Dart. Sets are collections that store unique values, meaning duplicates are automatically removed.
Sets are extremely useful in real-world scenarios such as removing duplicate entries, tracking unique users, filtering data, and enforcing uniqueness rules.
What Is a Set?
A set is an unordered collection of unique elements. Unlike lists, sets do not allow duplicate values.
If you try to add duplicate data, Dart automatically ignores it.
Creating a Set
Let’s create a set of registered user IDs in a system.
Set userIds = {101, 102, 103, 104};
print(userIds);
Each value in the set appears only once.
Automatic Removal of Duplicates
One of the biggest advantages of sets is automatic duplicate removal.
Set cities = {"Delhi", "London", "Tokyo", "London"};
print(cities);
Even though "London" is added twice, it appears only once in the set.
Real Example: Unique Product Categories
Imagine an e-commerce platform where product categories must be unique.
Set categories = {
"Electronics",
"Fashion",
"Books",
"Electronics"
};
print(categories);
This ensures there are no duplicate categories in the system.
Adding Elements to a Set
You can add elements to a set using the add() method.
categories.add("Sports");
print(categories);
If the value already exists, Dart will not add it again.
Removing Elements from a Set
You can remove elements using the remove() method.
categories.remove("Books");
print(categories);
This is useful for dynamic systems where data changes frequently.
Checking If an Element Exists
Sets are very efficient when checking for the presence of a value.
print(categories.contains("Fashion"));
print(categories.contains("Toys"));
This makes sets ideal for validation and filtering.
Iterating Through a Set
You can loop through a set using a for loop.
for (var category in categories) {
print(category);
}
Note that sets do not guarantee order.
Set Length
The length property returns the number of unique elements.
print("Total categories: ${categories.length}");
Set vs List (Quick Comparison)
- List → Allows duplicates, ordered, index-based
- Set → No duplicates, unordered, faster lookups
Real-World Use Cases
- Removing duplicate email addresses
- Tracking unique visitors
- Validating unique usernames
- Filtering duplicate records
📝 Practice Exercises
Exercise 1
Create a set of five programming languages and print it.
Exercise 2
Add a duplicate value to a set and observe the result.
Exercise 3
Check if a specific element exists in a set.
✅ Practice Answers
Answer 1
Set languages = {"Dart", "Python", "Java", "Go", "Rust"};
print(languages);
Answer 2
languages.add("Dart");
print(languages);
Answer 3
print(languages.contains("Java"));
print(languages.contains("C++"));
What’s Next?
In the next lesson, you will learn about Maps in Dart.
Maps store data as key-value pairs and are widely used in real-world applications.