Sub topic 11
Copying Dart Collections: Shallow Copies and Their Limits
This chapter assumes you know Dart variables, generics, null safety, and the basic operations on List, Map, and Set. It focuses on copying collections without accidentally sharing the collection you meant to duplicate.
What a shallow copy does
A shallow copy creates a new outer collection and copies its elements into that collection. Changing the new collection does not change the original collection's length or direct elements.
Common ways to make shallow copies include:
void main() {
final originalList = [1, 2, 3];
final copiedList = [...originalList];
final copiedListAgain = List<int>.from(originalList);
copiedList.add(4);
print(originalList); // [1, 2, 3]
print(copiedList); // [1, 2, 3, 4]
print(copiedListAgain); // [1, 2, 3]
}The spread operator (...) inserts every element from one collection into another. The List.from constructor creates a list from an iterable.
The same idea works for maps and sets:
void main() {
final originalMap = {'theme': 'dark', 'fontSize': 16};
final copiedMap = Map<String, Object>.from(originalMap);
final originalSet = {'dart', 'flutter'};
final copiedSet = Set<String>.from(originalSet);
copiedMap['fontSize'] = 18;
copiedSet.add('mobile');
print(originalMap); // {theme: dark, fontSize: 16}
print(copiedMap); // {theme: dark, fontSize: 18}
print(originalSet); // {dart, flutter}
print(copiedSet); // {dart, flutter, mobile}
}The copy has a different outer collection object. This makes it safe to add, remove, or replace direct elements in the copy.
The nested-object limit
A shallow copy does not recursively copy objects stored inside the collection. If an element is itself a list, map, set, or mutable custom object, both collections still refer to the same nested object.
void main() {
final original = <String, List<String>>{
'colors': ['red', 'blue'],
};
final copy = Map<String, List<String>>.from(original);
copy['colors']!.add('green');
print(original['colors']); // [red, blue, green]
print(copy['colors']); // [red, blue, green]
}The map was copied, but its value list was not. The ! says that the lookup result is known to be non-null at this point. The map's type allows a nullable result because a key might be absent.
A useful model is:
Avoiding shared nested state
To copy nested collections, copy each level that must be independent:
void main() {
final original = <String, List<String>>{
'colors': ['red', 'blue'],
};
final deepEnoughCopy = <String, List<String>>{
for (final entry in original.entries)
entry.key: List<String>.from(entry.value),
};
deepEnoughCopy['colors']!.add('green');
print(original['colors']); // [red, blue]
print(deepEnoughCopy['colors']); // [red, blue, green]
}This is sometimes called a deep copy, but the phrase can be misleading. The example copies the map and its lists. If those lists contained mutable objects, those objects would still be shared. A truly independent copy must define how every nested type is copied.
Choosing a copy strategy
- Use a spread or
List.from,Map.from, orSet.fromwhen only the outer collection needs independence. - Copy nested collections explicitly when their contents may change.
- Use immutable objects or unmodifiable views when sharing is intentional and mutation should be prevented.
- Do not use serialization as a generic deep-copy solution without checking type preservation, performance, and nullable values.
Exercise
After final b = [...a];, what happens if b.add(4) and a is [1, 2, 3]?
Show answer
b becomes [1, 2, 3, 4], while a remains [1, 2, 3]. The outer lists are separate.