Sub topic 11
Copying collections: shallow copies and their limits
This chapter assumes you can create lists, maps, and sets, use spread (...), and read generic types such as List<int>. By the end you will know which copy methods Dart offers, what "shallow" means, and how to copy nested data safely.
Assignment does not copy
Assigning a collection to a second variable copies the reference, not the contents. Both names point to the same object.
void main() {
final a = [1, 2, 3];
final b = a;
b.add(4);
print(a); // [1, 2, 3, 4]
print(identical(a, b)); // true
}final only stops you from rebinding the variable. It does not stop changes to the object. When a function receives a list and modifies it, the caller sees those changes. To avoid that, make a copy first.
Ways to copy
Each collection type has several ways to make a new, independent collection with the same elements.
void main() {
final list = [1, 2, 3];
final listCopies = [
List<int>.of(list),
List<int>.from(list),
[...list],
list.toList(),
];
final map = {'a': 1, 'b': 2};
final mapCopies = [
Map<String, int>.of(map),
Map<String, int>.from(map),
{...map},
];
final set = {1, 2, 3};
final setCopies = [
Set<int>.of(set),
Set<int>.from(set),
{...set},
set.toSet(),
];
list.add(4);
map['c'] = 3;
set.add(4);
print(listCopies.first); // [1, 2, 3]
print(mapCopies.first); // {a: 1, b: 2}
print(setCopies.first); // {1, 2, 3}
}Changing the originals afterwards does not affect any copy. The copies are new objects.
| Goal | List | Map | Set |
|---|---|---|---|
| Copy with a checked type | `List<T>.of(x)` | `Map<K, V>.of(x)` | `Set<T>.of(x)` |
| Copy and cast each element | `List<T>.from(x)` | `Map<K, V>.from(x)` | `Set<T>.from(x)` |
| Copy inside a literal | `[...x]` | `{...x}` | `{...x}` |
| Copy from any Iterable | `x.toList()` | not available | `x.toSet()` |
| Read-only copy | `List<T>.unmodifiable(x)` | `Map.unmodifiable(x)` | `Set.unmodifiable(x)` |
`of` versus `from`
of requires the source elements to already be of the target type, and the compiler checks this. from accepts any iterable and casts each element at runtime, so a mistake becomes a runtime error.
void main() {
final List<Object> mixed = [1, 'two'];
try {
final ints = List<int>.from(mixed);
print(ints);
} on TypeError {
print('from() cast each element and failed');
}
}Here List<int>.of(mixed) would not compile. Prefer of, toList(), or a spread unless you really need the runtime cast.
What "shallow" means
Every method above makes a shallow copy. The new collection is a separate object, but its elements are the same objects as in the original. For numbers, strings, and booleans this does not matter, because they are immutable. For elements that can change, such as lists, maps, or your own mutable classes, both collections share them.
void main() {
final original = [
[1, 2],
[3],
];
final copy = [...original];
copy.add([4]); // changes only the outer copy
print(original.length); // 2
copy[0].add(99); // changes the shared inner list
print(original); // [[1, 2, 99], [3]]
print(identical(original[0], copy[0])); // true
}Adding to the outer list affected only the copy. Changing an inner list showed up in both, because both outer lists hold the same inner list.
Deep copies by hand
Dart has no built-in deep copy. You write one that copies each level that can change. Collection for makes this short.
void main() {
final original = [
[1, 2],
[3],
];
final deep = [
for (final row in original) [...row],
];
deep[0].add(99);
print(original); // [[1, 2], [3]]
print(deep); // [[1, 2, 99], [3]]
final groups = <String, List<int>>{
'even': [2, 4],
'odd': [1, 3],
};
final groupsCopy = {
for (final e in groups.entries) e.key: [...e.value],
};
groupsCopy['even']!.add(6);
print(groups['even']); // [2, 4]
print(groupsCopy['even']); // [2, 4, 6]
}You copy only as deep as the data is mutable. In groups, the keys are strings and need no copy. Only the value lists do.
For your own classes, give them a copy method or constructor that copies their mutable fields, then map over the collection:
class Task {
String title;
List<String> tags;
Task(this.title, this.tags);
Task copy() => Task(title, [...tags]);
}
void main() {
final tasks = [
Task('write', ['draft']),
Task('test', []),
];
final shallow = [...tasks];
final deep = [for (final t in tasks) t.copy()];
tasks[0].title = 'edit';
tasks[0].tags.add('urgent');
print(shallow[0].title); // edit
print(deep[0].title); // write
print(deep[0].tags); // [draft]
}Copies can change mutability
A copy does not inherit the mutability of its source. The copy methods return growable collections unless you ask otherwise, so copying is also the usual way to get a modifiable collection from a const one.
void main() {
const fixed = [1, 2, 3];
final growable = [...fixed];
growable.add(4);
print(growable); // [1, 2, 3, 4]
final noGrow = fixed.toList(growable: false);
try {
noGrow.add(5);
} on UnsupportedError {
print('fixed-length copy cannot grow');
}
}Unmodifiable copies versus views
List.unmodifiable makes a copy that rejects changes. UnmodifiableListView from dart:collection is different. It wraps the original list and stops writes through the view, but it still shows later changes to the source.
import 'dart:collection';
void main() {
final source = [1, 2, 3];
final snapshot = List<int>.unmodifiable(source);
final view = UnmodifiableListView<int>(source);
source.add(4);
print(snapshot); // [1, 2, 3]
print(view); // [1, 2, 3, 4]
try {
snapshot.add(5);
} on UnsupportedError {
print('snapshot is read-only');
}
}Use a snapshot when you want a stable value. Use a view when you want to expose live data without letting callers modify it, such as returning a private list from a getter.
An unmodifiable collection is also shallow. Its own structure is locked, but you can still change a mutable element inside it.
Common errors
- Copying a nested structure once.
[...rows]copies only the outer list. Copy every level that holds mutable data. - Assuming a copy is deep because it prints the same. Printing cannot show shared references. Use
identical(a[0], b[0])to check. - Returning a private list from a getter. Callers can change your internal state. Return an
UnmodifiableListViewor a copy. - Mutating set elements or map keys after insertion. A set or map places each element by its
hashCode. If a shared mutable element changes in a way that alters its hash, lookups in either collection can fail. Use immutable keys. - Using
fromwithout a reason. It defers type errors to runtime. - Copying inside a hot loop. Every copy costs time and memory proportional to the number of elements. Copy once at a boundary, such as a function entry or a state update, not on every iteration.
Exercise
Given final a = [[1], [2]]; final b = List<List<int>>.of(a); b[0].add(9); b.add([3]);, what are a and b after these statements? Then write one expression that makes b a copy that does not share inner lists with a.
Show answer
a is [[1, 9], [2]] and b is [[1, 9], [2], [3]]. List.of is a shallow copy, so b[0] and a[0] are the same inner list, and adding 9 shows up in both. Adding [3] changed only b's outer list. A copy that does not share inner lists is [for (final row in a) [...row]].
Exercise
A class keeps final List<String> _items = [];. Which getter lets callers read the items, always see the latest contents, and prevent them from modifying the list: List<String> get items => List.unmodifiable(_items); or List<String> get items => UnmodifiableListView(_items);? State the cost of the other one.
Show answer
UnmodifiableListView(_items) (from dart:collection) shows the latest contents because it wraps the original list without copying. List.unmodifiable(_items) builds a new snapshot on every call, which costs time proportional to the list length, and the snapshot does not reflect later changes.