Sub topic 7
Lists, Sets, and Maps
This chapter assumes you know Dart variables, final and const, null safety, and function syntax. It covers the three core collection types: how to create them, how to transform them, and which mistakes cause runtime errors.
Choosing a collection
Each type answers a different question.
| Type | Ordered | Duplicates | Lookup by | Literal |
|---|---|---|---|---|
| `List<E>` | Yes, by index | Allowed | Position (`list[0]`) | `[1, 2, 3]` |
| `Set<E>` | Insertion order by default | Ignored | Membership (`contains`) | `{1, 2, 3}` |
| `Map<K, V>` | Insertion order by default | Keys unique | Key (`map['a']`) | `{'a': 1}` |
Literals and type inference
Dart infers the element type from the literal. Write the type argument explicitly when the collection starts empty, because otherwise Dart cannot infer anything useful.
void main() {
final names = ['Ada', 'Linus']; // List<String>
names.add('Grace');
final ids = <int>[]; // empty, type given
final tags = {'dart', 'flutter'}; // Set<String>
final Set<int> seen = {}; // empty Set, via the variable type
final stock = <String, int>{'apple': 3};
print('$names $ids $tags $seen $stock');
}Empty braces {} with no type information create a Map, not a Set. To get an empty set, write <int>{} or declare Set<int>.
Mutability: growable, fixed-length, and constant
A list literal is growable. Other constructors and const produce lists with restrictions, and breaking them throws UnsupportedError at runtime, not at compile time.
void main() {
final fixed = List<int>.filled(3, 0); // length is locked at 3
fixed[0] = 1; // allowed
const frozen = [1, 2, 3]; // deeply immutable
try {
frozen.add(4);
} on UnsupportedError {
print('const list cannot grow');
}
final copy = List<int>.of(frozen); // new growable list
copy.add(4);
print('$fixed $copy'); // [1, 0, 0] [1, 2, 3, 4]
}final only prevents reassigning the variable. A final list can still change its contents. const makes the object itself immutable, and List.unmodifiable(source) gives a runtime-immutable copy when the values are not known at compile time.
Collection `if`, `for`, and spread
Inside a literal you can use if, for, and spread operators. This builds a list declaratively, without a mutable accumulator.
void main() {
final base = [1, 2, 3];
List<int>? extra; // may be null
final isAdmin = true;
final all = [
...base, // spread
...?extra, // null-aware spread: skipped if null
if (isAdmin) 99, // conditional element
for (var i = 0; i < 2; i++) i * 10,
];
print(all); // [1, 2, 3, 99, 0, 10]
}A plain ...extra with a nullable value is a compile error, so use ...? for nullable sources. These forms work in Set and Map literals too. In maps, the if and for branches produce key: value pairs.
Transforming with iterable methods
List and Set are both Iterable, so they share a set of methods that return new values.
| Method | Result | Notes |
|---|---|---|
| `map(f)` | `Iterable` of transformed items | Lazy |
| `where(test)` | `Iterable` of matching items | Lazy |
| `fold(init, f)` | One accumulated value | Works on empty input |
| `reduce(f)` | One accumulated value | Throws `StateError` when empty |
| `any(test)` / `every(test)` | `bool` | Short-circuit |
| `first` / `last` / `single` | One element | Throw `StateError` if the rule fails |
| `firstWhere(test, orElse: ...)` | First match | Throws if none and no `orElse` |
| `toList()` / `toSet()` | Concrete collection | Forces evaluation |
void main() {
final prices = [4, 8, 15, 16, 23, 42];
final total = prices.fold<int>(0, (sum, p) => sum + p);
print(total); // 108
print(prices.any((p) => p > 40)); // true
print(prices.every((p) => p.isEven)); // false
final labels = prices.map((p) => '\$$p').take(2).toList();
print(labels); // [$4, $8]
final cheap = prices.firstWhere((p) => p < 0, orElse: () => -1);
print(cheap); // -1
}Laziness
map and where do not run until something consumes the result. The closure runs again every time you iterate the same lazy Iterable.
void main() {
var calls = 0;
final lazy = [1, 2, 3].map((n) {
calls++;
return n * 2;
});
print(calls); // 0, nothing has run yet
lazy.toList();
print(calls); // 3
lazy.toList();
print(calls); // 6, it ran again
}Call toList() once when you need to reuse the result or when the closure has side effects.
Sets
A Set rejects duplicates, and add returns false when the element was already present. Set algebra is built in.
void main() {
final a = {1, 2, 3};
final b = {3, 4};
print(a.add(3)); // false
print(a.union(b)); // {1, 2, 3, 4}
print(a.intersection(b)); // {3}
print(a.difference(b)); // {1, 2}
print(a.contains(2)); // true
}Use list.toSet().toList() to remove duplicates while keeping first-seen order. Elements are compared with == and hashCode, so custom classes used in a Set must override both. Otherwise two equal-looking objects are treated as different.
Maps
Indexing a map with [] returns V?, because the key may be missing. Handle that with ?? or !, as you would with any nullable value.
void main() {
final stock = <String, int>{'apple': 3, 'pear': 0};
final apples = stock['apple']; // int?
final kiwis = stock['kiwi'] ?? 0; // 0
print('$apples $kiwis'); // 3 0
stock.putIfAbsent('kiwi', () => 10); // adds only if missing
stock.update('apple', (n) => n + 1); // key must exist
stock.update('plum', (n) => n + 1, ifAbsent: () => 1);
for (final MapEntry(:key, :value) in stock.entries) {
print('$key: $value');
}
// apple: 4, pear: 0, kiwi: 10, plum: 1
}Other members you will use often:
containsKey(k)tests for a key. Checkingmap[k] == nullcannot tell a missing key from a key stored with anullvalue.remove(k)deletes a key and returns the old value ornull.keysandvaluesare lazy iterables that reflect the map.map.map((k, v) => MapEntry(k, v * 2))builds a new map, andMap.fromEntriesandMap.fromIterablebuild maps from other data.
The default map is a LinkedHashMap, so iteration follows insertion order. Do not depend on any other ordering unless you choose a SplayTreeMap, which sorts by key.
Common errors
- Changing a collection while iterating it. Calling
addorremoveinside afor (final x in list)loop throwsConcurrentModificationError. UseremoveWhere,retainWhere, or iterate over a copy with[...list]. - Out-of-range access.
list[5]on a three-element list throwsRangeError. Checklengthor useelementAtOrNull(fromdart:corein Dart 3). - Shared elements from
List.filled.List.filled(2, <int>[])puts the same inner list in both slots. UseList.generate(2, (_) => <int>[]). - Expecting value equality.
[1, 2] == [1, 2]isfalsebecause lists compare by identity. Twoconstlists with equal contents are the same object, soconst [1, 2] == const [1, 2]istrue. For deep comparison of runtime lists, useDeepCollectionEqualityfrompackage:collection. - Forgetting that
sortreturnsvoid.list.sort()reorders in place. Chaininglist.sort().toList()is a compile error. Copy first with[...list]..sort(). - Empty
{}assumed to be a Set. See the literals section.
Exercise
What does this program print, and why? final m = <String, int>{'a': 1}; print(m['b'] == null); m['b'] = 0; print(m['b'] == null); print(m.containsKey('b'));
Show answer
It prints true, false, true. The key 'b' is missing at first, so the lookup returns null. After the assignment the value is 0, which is not null. containsKey('b') is true because the key now exists.
Exercise
Write a single list literal that contains all elements of a (a List<int>), then all elements of b (a List<int>? that may be null), then the number 0 only when includeZero is true.
Show answer
[...a, ...?b, if (includeZero) 0]. The null-aware spread ...?b skips b when it is null, and the collection if adds 0 only when the condition holds.