In Dart, a Set is an unordered collection of unique items—meaning it automatically removes duplicates. Sets are useful when you want to store elements without repetition and don’t care about the order.
You can declare and initialize a Set in a few ways:
Using a literal:
void main() {
Set fruits = {'Apple', 'Banana', 'Mango'};
print(fruits); // {Apple, Banana, Mango}
}
Using the Set constructor:
Set numbers = Set();
numbers.add(1);
numbers.add(2);
numbers.add(2); // duplicate, will be ignored
print(numbers); // {1, 2}
Here, even if you try to add duplicate values, the Set keeps only unique elements. Sets also have methods like add(), remove(), contains(), and length, making it convenient to manage collections of distinct items.
In practical projects, I’ve used Sets when I needed to filter out duplicate entries from user input or API data. For example, when storing tags for blog posts, a Set ensures that each tag appears only once, avoiding redundancy.
One challenge I faced was that Sets are unordered, so if you need elements in a specific order, you must convert the Set to a List first. For example:
List sortedFruits = fruits.toList()..sort();
print(sortedFruits); // [Apple, Banana, Mango]
An alternative approach is to use a List if you need duplicates or care about the order, but for unique collections, Sets are more efficient and cleaner.
Sets are lightweight and extremely useful when working with unique datasets.
