Sub topic 2
Lists: ordered, indexed sequences
A List is Dart's most common collection. It holds elements in a fixed order, and each element has an integer position called an index. This chapter assumes you know basic Dart syntax, generics notation such as List<int>, and the idea of a nullable type. Null-safe lookups, spread, sorting, and copying each get their own chapter, so this one covers the core of lists: creating them, reading them, changing them, and the errors you will hit.
The shape of a list
Indexes start at 0. A list of length n has valid indexes 0 through n - 1. The list also remembers the order you put elements in, and it allows duplicates.
Reading or writing by index is fast. It takes the same time no matter how long the list is. Searching for a value with contains or indexOf is slower, because Dart checks elements one by one from the start.
Creating lists
The usual way is a list literal in square brackets. Dart infers the element type from the contents.
void main() {
final fruits = ['apple', 'banana']; // List<String>
final ids = <int>[]; // empty, explicitly List<int>
final List<double> prices = []; // type comes from the declaration
var loose = []; // List<dynamic>, usually not what you want
print(fruits.runtimeType); // List<String>
print(ids.isEmpty); // true
print(prices.length); // 0
loose.add('text');
loose.add(42);
print(loose); // [text, 42]
}An empty literal with no type information becomes List<dynamic>. That type accepts anything and turns off most type checking, so give empty lists a type with <int>[] or a declared type.
The constructors cover cases a literal cannot:
void main() {
final zeros = List<int>.filled(3, 0);
print(zeros); // [0, 0, 0]
final squares = List<int>.generate(4, (i) => i * i);
print(squares); // [0, 1, 4, 9]
final copy = List<int>.of(squares);
print(copy); // [0, 1, 4, 9]
}List.filled(length, value)makes a list of a given length with the same value in every slot.List.generate(length, builder)callsbuilderwith each index and stores the result.List.of(iterable)builds a new list from any iterable.
The shared-element trap
List.filled stores the same object in every slot. That is harmless for numbers and strings, which you cannot change in place. It is a bug when the value is a mutable object such as another list.
void main() {
final shared = List.filled(2, <int>[]);
shared[0].add(1);
print(shared); // [[1], [1]], both slots hold the same inner list
final separate = List.generate(2, (_) => <int>[]);
separate[0].add(1);
print(separate); // [[1], []]
}Use List.generate whenever each slot needs its own object.
Adding elements
add appends one element to the end. insert(index, value) places an element at a position and shifts later elements right. addAll and insertAll do the same for many elements at once.
void main() {
final fruits = <String>['apple', 'banana'];
fruits.add('cherry');
fruits.insert(0, 'apricot');
print(fruits); // [apricot, apple, banana, cherry]
print(fruits[1]); // apple
fruits.removeAt(1);
print(fruits.length); // 3
}insert accepts an index from 0 up to and including length. Inserting at length is the same as add. Inserting at the front or middle is slower than add, because every later element has to shift.
Reading elements
Use the square-bracket operator to read by index. The list also has getters for common positions.
void main() {
final scores = [90, 85, 70];
scores[1] = 88; // assignment by index replaces an element
print(scores.first); // 90
print(scores.last); // 70
print(scores.length); // 3
print(scores.isNotEmpty); // true
print(scores.indexOf(70)); // 2
print(scores.indexOf(100)); // -1, meaning not found
print(scores.contains(88)); // true
print(scores.sublist(1)); // [88, 70]
print(scores.sublist(0, 2)); // [90, 88]
}sublist(start, end)returns a new list. Theendindex is excluded, and leaving it out means "to the end".indexOfreturns the first matching position, or-1when nothing matches. It uses==to compare, which matters for custom classes (see the equality chapter).getRange(start, end)returns a lazy view of a section instead of a new list.
Out-of-range errors
Dart checks every index. A bad index throws a RangeError at run time, and there is no wrap-around or silent null.
void main() {
final scores = [90, 85, 70];
try {
print(scores[3]);
} on RangeError {
print('index out of range');
}
final empty = <int>[];
try {
print(empty.first);
} on StateError {
print('no element in an empty list');
}
}Negative indexes also throw. first, last, and single throw a StateError on an empty list, so check isEmpty first or use firstOrNull and lastOrNull. Those two are available on iterables from Dart 3 via dart:core, and they return null instead of throwing.
Removing elements
Each removal method answers a different question:
| Method | What it removes | Returns |
|---|---|---|
| `remove(value)` | The first element equal to `value` | `true` if something was removed |
| `removeAt(index)` | The element at `index` | The removed element |
| `removeLast()` | The last element | The removed element |
| `removeWhere(test)` | Every element for which `test` is true | Nothing |
| `removeRange(start, end)` | Elements from `start` up to `end` | Nothing |
| `clear()` | All elements | Nothing |
void main() {
final tasks = ['a', 'b', 'c', 'd', 'e'];
print(tasks.remove('b')); // true
print(tasks.remove('zzz')); // false
print(tasks.removeAt(0)); // a
print(tasks.removeLast()); // e
print(tasks); // [c, d]
tasks.addAll(['x', 'y']);
tasks.removeWhere((t) => t == 'x');
print(tasks); // [c, d, y]
tasks.insertAll(1, ['p', 'q']);
print(tasks); // [c, p, q, d, y]
tasks.clear();
print(tasks.isEmpty); // true
}remove returns a bool and never throws when the value is missing. removeAt and removeLast do throw RangeError or StateError on an invalid index or an empty list.
Lists and types
A list literal has a static element type, and Dart enforces it. List<int> rejects a string at compile time. Nested lists work the same way, so a table of numbers is a List<List<int>>.
void main() {
final grid = <List<int>>[
[1, 2, 3],
[4, 5, 6],
];
print(grid[1][2]); // 6
grid[0][0] = 10;
print(grid); // [[10, 2, 3], [4, 5, 6]]
}The first index picks the row, and the second picks the element inside that row.
A list of int? can hold null elements, which is different from a list that is itself null. Chapter five of this tutorial covers that distinction.
Common mistakes
- Using
var x = []and then relying on type checks. The list isList<dynamic>, so errors appear at run time instead of compile time. - Using
List.filledwith a mutable value, so all slots share one object. - Reading
list[list.length]. The last valid index islength - 1, or uselast. - Changing a list's length while a
for-inloop is walking over it. Dart throws aConcurrentModificationErroron the next step of the loop. Build a new list or useremoveWhereinstead. - Assuming
==compares contents. Two lists with the same elements are still different objects, so[1, 2] == [1, 2]isfalse.
Practice
Exercise
What does this program print, and why? void main() { final rows = List.filled(2, <String>[]); rows[0].add('x'); rows.add(['y']); print(rows); print(rows.length); }
Show answer
It prints [[x], [x], [y]] and then 3. List.filled puts the same inner list object in both slots, so adding 'x' through rows[0] also shows up in rows[1]. The later rows.add(['y']) appends a third, separate list, so the length is 3. Using List.generate(2, (_) => <String>[]) would give each slot its own inner list.
Exercise
A list named queue holds ['a', 'b', 'c']. Which single call returns the element 'a' and also removes it, and what does queue.indexOf('z') return?
Show answer
queue.removeAt(0) returns 'a' and removes it, leaving ['b', 'c']. queue.indexOf('z') returns -1 because 'z' is not in the list.