Dart Lists
A List<E> is an ordered collection of elements of type E, accessed by a zero-based index. Lists are the most-used collection in Dart — what other languages call arrays.
Creating lists
void main() {
var primes = [2, 3, 5, 7]; // List<int> inferred
List<String> names = ['An', 'Binh'];
var empty = <double>[]; // typed empty list
var zeros = List.filled(4, 0); // fixed length
var squares = List.generate(5, (i) => i * i);
var copy = List.of(primes);
const fixed = ['read', 'only']; // unmodifiable
print(primes);
print(names);
print(empty);
print(zeros);
print(squares);
print(copy);
print(fixed);
}[2, 3, 5, 7]
[An, Binh]
[]
[0, 0, 0, 0]
[0, 1, 4, 9, 16]
[2, 3, 5, 7]
[read, only]
Note:
List.filled(4, 0)is fixed-length —addthrows. Passgrowable: trueif you need to grow it. And bewareList.filled(3, []): all three slots share the same inner list. UseList.generate(3, (_) => [])instead.
Reading elements
void main() {
var colors = ['red', 'green', 'blue', 'cyan'];
print(colors[0]);
print(colors.first);
print(colors.last);
print(colors.length);
print(colors.indexOf('blue'));
print(colors.contains('pink'));
print(colors.sublist(1, 3));
print(colors.reversed.toList());
print(colors.elementAtOrNull(10));
try {
print(colors[10]);
} on RangeError catch (e) {
print('RangeError: ${e.message}');
}
}red
red
cyan
4
2
false
[green, blue]
[cyan, blue, green, red]
null
RangeError: Invalid value
Out-of-range indexes throw a RangeError — there's no silent undefined like in JavaScript. elementAtOrNull (an extension method added in Dart 3) returns null instead.
Modifying lists
| Method | Effect |
|---|---|
add(x), addAll(xs) |
Append |
insert(i, x), insertAll(i, xs) |
Insert at index |
remove(x) |
Remove first occurrence, returns bool |
removeAt(i), removeLast() |
Remove by position, returns the element |
removeWhere(test) |
Remove all matching |
list[i] = x |
Replace |
clear() |
Remove everything |
sort([compare]) |
Sort in place |
shuffle() |
Random order (not deterministic!) |
void main() {
var queue = ['Hoa', 'Tuan'];
queue.add('Nam');
queue.insert(0, 'VIP');
queue.addAll(['Mai', 'Duc']);
print(queue);
queue.remove('Tuan');
var served = queue.removeAt(0);
print('served $served, waiting: $queue');
queue.removeWhere((n) => n.startsWith('D'));
print(queue);
queue[0] = 'Hoa (moved)';
print(queue);
}[VIP, Hoa, Tuan, Nam, Mai, Duc]
served VIP, waiting: [Hoa, Nam, Mai, Duc]
[Hoa, Nam, Mai]
[Hoa (moved), Nam, Mai]
remove deletes by value, removeAt by position, and removeWhere deletes every element that passes the test — double-check what a bulk removal will hit.
Sorting
sort() uses natural ordering for numbers and strings. Pass a comparator (a, b) => … returning negative, zero or positive for custom orders:
void main() {
var nums = [42, 7, 19, 3];
nums.sort();
print(nums);
var words = ['banana', 'Fig', 'apple', 'cherry'];
words.sort();
print(words); // uppercase sorts before lowercase
words.sort((a, b) => a.toLowerCase().compareTo(b.toLowerCase()));
print(words);
words.sort((a, b) => b.length.compareTo(a.length)); // longest first
print(words);
}[3, 7, 19, 42]
[Fig, apple, banana, cherry]
[apple, banana, cherry, Fig]
[banana, cherry, apple, Fig]
Lists of lists
void main() {
var board = List.generate(3, (r) => List.generate(3, (c) => r * 3 + c + 1));
board[1][1] = 0;
for (final row in board) {
print(row.join(' '));
}
}1 2 3
4 0 6
7 8 9
Lists are reference types
Assigning a list to another variable copies the reference, not the elements. Both names see the same changes. Use List.of(list) or [...list] to copy.
var a = [1, 2];
var b = a; // same list
var c = [...a]; // new list
b.add(3); // a is now [1, 2, 3]; c is still [1, 2]Test yourself
What happens when you call add on a list created with List.filled(3, 0)?
- The element is added
- It throws because the list is fixed-length
- It replaces the last element
- Compile error
What does list[99] do on a 3-element list?
- Returns null
- Returns undefined
- Throws a RangeError
- Grows the list
Which comparator sorts strings from longest to shortest?
- (a, b) => a.length.compareTo(b.length)
- (a, b) => b.length.compareTo(a.length)
- (a, b) => a.compareTo(b)
- (a, b) => a.length - b