In Dart, both List and Set are used to store collections of items, but they have key differences in behavior and use cases.
- Order:
- List maintains the order of elements. The first item you add stays at index 0, the second at index 1, and so on.
- Set is unordered. The elements have no guaranteed order.
- Duplicates:
- List allows duplicate values. You can have the same item multiple times.
- Set automatically removes duplicates. Every element is unique.
- Access:
- List allows indexed access, meaning you can get an element using its position:
list[0]. - Set does not support indexed access directly because it’s unordered. You typically iterate using loops or methods like
contains().
- List allows indexed access, meaning you can get an element using its position:
- Performance:
- Set is more efficient for checking if an element exists because it uses hashing internally.
- List requires scanning the elements sequentially to find a value, so it’s slower for lookups in large datasets.
Example:
filename.dart
void main() {
List numbersList = [1, 2, 2, 3];
Set numbersSet = {1, 2, 2, 3};
print(numbersList); // [1, 2, 2, 3] → preserves duplicates & order
print(numbersSet); // {1, 2, 3} → unique elements, unordered
}
Practical use:
- I use Lists when order matters, like displaying a user’s messages in sequence.
- I use Sets when I need to store unique items, like tags for blog posts or removing duplicates from API data.
Limitation:
- If you need both order and uniqueness, a plain Set won’t help. In that case, you can use a LinkedHashSet, which preserves insertion order while keeping elements unique.
