Search⌘ K
AI Features

Dart's Collection: Sets

Explore Dart's Set collection to manage unique, unordered data effectively. Learn to create typed sets, manipulate items while preventing duplicates, and perform operations like union and intersection for comparing data groups.

In the previous lesson, we explored how Lists store ordered sequences of data. However, we sometimes need a collection where uniqueness is more important than order. A Set is a collection of unique, unordered items. Because a Set is unordered, its elements do not have fixed index positions. Because it requires uniqueness, a Set automatically prevents duplicate values.

Creating a set

We create a Set using curly braces {}. To ensure Dart understands exactly what data type the Set will hold, we use a typed literal by placing the data type in angle brackets <Type> right before the curly braces.

When creating an empty set, we must specify the data type. If we simply use empty curly braces {} without a type, Dart defaults to creating a Map, which is a different collection type entirely.

Let us look at how to define both populated and empty sets.

Dart
void main() {
final fruits = <String>{'apple', 'banana', 'orange'};
final emptySet = <int>{};
print(fruits);
print(emptySet);
}
  • Line 2: We use a set literal to create a collection of unique, unordered text values. We strictly type this structure to hold only String data and bind it to an immutable final variable, ensuring the reference itself cannot be ...