Search⌘ K
AI Features

Dart's Collection: Sets

Explore Dart Sets to manage collections of unique, unordered items. Learn to create and manipulate sets, add multiple elements, handle duplicates, and perform advanced operations like intersection and union.

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 ...