Sub topic 7
Lists, Sets, and Maps
This chapter assumes that you know Dart variables, expressions, functions, and basic control flow. It focuses on choosing the right collection, transforming values, and avoiding common type and lookup errors.
Choosing a collection
A collection stores multiple values. Dart provides three main collection types:
| Collection | Main property | Typical use |
|---|---|---|
| `List<T>` | Ordered values, accessed by index | Items in display order |
| `Set<T>` | Unique values, no meaningful index | Tags or membership checks |
| `Map<K, V>` | Key-value pairs | Looking up a value by key |
The type parameters, such as String in List<String>, describe the kind of values a collection accepts.
void main() {
final names = <String>['Ada', 'Linus', 'Grace'];
final tags = <String>{'dart', 'flutter', 'dart'};
final scores = <String, int>{
'Ada': 95,
'Linus': 88,
};
print(names[0]); // Ada
print(tags); // {dart, flutter}
print(scores['Ada']); // 95
}The set contains only one copy of 'dart'. A list preserves insertion order and supports indexing. A map uses keys instead of numeric positions.
Building and transforming lists
Collection literals create collections directly. A list can be mutable even when the variable holding it is declared with final. final prevents reassignment of the variable, but it does not freeze the list.
void main() {
final numbers = [1, 2, 3, 4];
numbers.add(5);
final doubled = [for (final n in numbers) n * 2];
final evens = numbers.where((n) => n.isEven).toList();
final labels = numbers.map((n) => 'Item $n').toList();
print(numbers);
print(doubled);
print(evens);
print(labels);
}where and map return an Iterable, which is a sequence that can be traversed. Call .toList() when an actual List is required.
The spread operator copies elements from another collection into a new literal:
final defaults = ['Home', 'Settings'];
final pages = ['Dashboard', ...defaults, 'Help'];Sets and maps
Use a set when duplicates should disappear or when membership matters more than position.
final permissions = {'read', 'write'};
permissions.add('read');
print(permissions.contains('write')); // trueMap keys must be unique. Assigning an existing key replaces its value.
final stock = {'pens': 10, 'books': 4};
stock['pens'] = 8;
stock['paper'] = 20;
for (final entry in stock.entries) {
print('${entry.key}: ${entry.value}');
}A missing map key returns null, so the value type often needs to be nullable when a lookup may fail.
Common errors
- Reading
list[list.length]causes a range error. The last valid index islist.length - 1. - Assuming a set has stable index-based order makes code fragile.
- Forgetting
.toList()leaves anIterable, which may not support list operations such as indexing. - Using mutable collections as map keys can produce confusing lookup behavior. Prefer stable key values such as strings, numbers, or immutable objects.
Exercise
What collection should you use for unique email addresses when you only need to check whether an address is present?
Show answer
Use a Set<String>, because it removes duplicates and provides contains for membership checks.