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.
We'll cover the following...
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.
Line 2: We use a set literal to create a collection of unique, unordered text values. We strictly type this structure to hold only
Stringdata and bind it to an immutablefinalvariable, ensuring the reference itself cannot be ...