Sub topic 10
Growable, fixed-length, const, and unmodifiable collections
This chapter assumes you can create lists, maps, and sets from literals and call their basic methods. It also assumes you know what final means and what an exception is. Here you will learn which operations a Dart collection allows. Two collections can have the same type, List<int>, and still disagree about whether add works.
Four kinds of "list"
The type List<int> describes what you can read from a list. It does not say whether you can change the list's length or its elements. That depends on how the list was created at runtime.
| Kind | Typical creation | Change length? | Replace elements? |
|---|---|---|---|
| Growable | `[1, 2, 3]`, `List.of(x)`, `x.toList()` | Yes | Yes |
| Fixed-length | `List.filled(3, 0)`, `List.generate(3, f, growable: false)`, `x.toList(growable: false)` | No | Yes |
| Unmodifiable | `List.unmodifiable(x)` | No | No |
| Const | `const [1, 2, 3]` | No | No |
Maps and sets have the same split, with two differences. They have no fixed-length variant, and Map.unmodifiable and Set.unmodifiable exist alongside const {} literals.
An operation that a collection does not support throws an UnsupportedError. The compiler does not catch this, so you find out at runtime.
Seeing the differences
The program below tries the same two operations on each kind and reports what happened.
void tryChange(String label, void Function() action) {
try {
action();
print('$label: ok');
} on UnsupportedError {
print('$label: UnsupportedError');
}
}
void main() {
final growable = [1, 2, 3];
final fixed = List<int>.filled(3, 0);
const constant = [1, 2, 3];
final frozen = List<int>.unmodifiable([1, 2, 3]);
tryChange('growable add', () => growable.add(4));
tryChange('fixed add', () => fixed.add(4));
tryChange('fixed set', () => fixed[0] = 9);
tryChange('const set', () => constant[0] = 9);
tryChange('frozen set', () => frozen[0] = 9);
}The output is:
growable add: ok
fixed add: UnsupportedError
fixed set: ok
const set: UnsupportedError
frozen set: UnsupportedErrorThe fixed-length list rejects add but accepts fixed[0] = 9. "Fixed-length" restricts the length only. Any method that changes the length throws on such a list, including add, insert, remove, removeAt, removeLast, clear, and length = n.
Growable lists and where they come from
A list literal is growable. Most constructors and conversions also produce growable lists, and toList takes an optional growable argument that defaults to true.
void main() {
final source = {3, 1, 2};
final a = source.toList(); // growable
final b = source.toList(growable: false); // fixed-length
a.add(4);
print(a); // [3, 1, 2, 4]
try {
b.add(4);
} on UnsupportedError {
print('b is fixed-length');
}
}Fixed-length lists are useful when you know the size in advance. They also signal that the length will not change. The memory savings are small, so choose them for intent, not for speed.
Const collections
A const collection is created at compile time. It is immutable, and every element must also be a compile-time constant.
void main() {
const a = [1, 2];
const b = [1, 2];
print(identical(a, b)); // true, both names refer to one object
print(identical(<int>[1, 2], <int>[1, 2])); // false, two separate lists
}Equal const values are canonicalized, which means the program keeps one shared object per distinct value. You can safely use const collections as default values or shared lookup tables, because no code can modify them.
These rules are easy to confuse:
conston a variable declares the variable and makes its value a compile-time constant. Writingconst [1, 2]creates an immutable list even if the variable is declared withfinalorvar.finalon a variable only stops reassignment of the variable. It says nothing about the object. Afinallist can still grow.- Elements must be constant too.
const [DateTime.now()]does not compile. - Inside a
constliteral, you can use spreads of other const collections andiforforwith constant conditions. The result is still const.
A variable typed List<int> can hold a const list, and the compiler will not warn you when you call add on it. This matters most when a function accepts a list and mutates it:
void addDefaults(List<String> names) {
names.add('guest'); // throws if the caller passed a const list
}
void main() {
addDefaults(['ana']); // fine
try {
addDefaults(const ['ana']);
} on UnsupportedError {
print('caller passed an immutable list');
}
}If a function should not mutate its argument, do not mutate it. Build a new list and return that instead.
Unmodifiable copies versus unmodifiable views
List.unmodifiable(source) creates a new list from the elements of source, and that new list refuses modification. Later changes to source do not affect it. Set.unmodifiable and Map.unmodifiable work the same way.
UnmodifiableListView from dart:collection is different. It wraps an existing list without copying it. The wrapper refuses changes, but if someone changes the underlying list, the view shows the change.
import 'dart:collection';
void main() {
final source = [1, 2, 3];
final view = UnmodifiableListView(source);
final copy = List<int>.unmodifiable(source);
source.add(4);
print(view.length); // 4, the view reflects the source
print(copy.length); // 3, the copy was taken earlier
}Both are used to expose internal state safely. A class that keeps a private list can return an UnmodifiableListView from a getter. This is cheap, because there is no copying, and callers can read but not write. The trade-off is that the view can change while a caller is iterating over it. Return an unmodifiable copy when the caller needs a stable snapshot.
import 'dart:collection';
class Cart {
final List<String> _items = [];
List<String> get items => UnmodifiableListView(_items);
void add(String item) => _items.add(item);
}
void main() {
final cart = Cart()..add('tea');
print(cart.items); // [tea]
try {
cart.items.add('hack');
} on UnsupportedError {
print('cannot modify through the getter');
}
}Immutability is shallow
None of these protections reach inside the elements. An unmodifiable list of lists stops you from changing the outer list. The inner lists are still whatever they were.
void main() {
final inner = [1];
final frozen = List<List<int>>.unmodifiable([inner]);
inner.add(2);
frozen.first.add(3);
print(frozen); // [[1, 2, 3]]
}const is the exception, because it is deep. Every element of a const collection must itself be a constant, so everything inside is immutable.
Choosing a kind
The flowchart below shows how to decide between the kinds. It starts from what you need to guarantee.
Common mistakes
- Assuming
finalmeans immutable. It only locks the variable. - Passing a
constlist to a function that sorts or appends in place. Sorting a const list also throws, becausesortreorders elements. - Calling
addon the result ofList.filled. If you need to grow it, use[]andadd, orList.generate(n, f)with the default growable setting. - Returning a private list directly from a getter. Callers can then change your object's internal state.
- Expecting an unmodifiable list of mutable objects to be safe. Only the outer structure is locked.
Exercise
A class stores final List<int> _scores = []; and exposes List<int> get scores => _scores;. Another developer writes account.scores.add(100), and the class's state changes. Write a one-line getter that blocks this without copying the list. Then say what the caller sees if the class later adds a score while the caller is looping over scores.
Show answer
Use List<int> get scores => UnmodifiableListView(_scores); and import dart:collection. The caller can then read but not write, and add throws UnsupportedError. Because the view wraps the original list without copying it, the loop sees the new score. Adding to a list while iterating over it normally throws a ConcurrentModificationError, so a snapshot is safer for callers that iterate. For a snapshot, return List.unmodifiable(_scores), which copies on every call.
Exercise
Which of these lines throws an UnsupportedError at runtime? (a) [1, 2, 3].removeLast(); (b) List<int>.filled(2, 0)[1] = 5; (c) const [3, 1, 2].sort(); (d) List<int>.filled(2, 0).removeLast();
Show answer
Lines (c) and (d) throw. Line (a) works because a list literal is growable. Line (b) works because a fixed-length list allows changing elements. Line (c) throws because sorting rewrites the elements of an immutable const list. Line (d) throws because removeLast changes the length of a fixed-length list.