Sub topic 2
Lists: Ordered, Indexed Sequences
Assume you know basic Dart variables, functions, control flow, generics such as List<int>, and nullable types such as int?. A List<T> is an ordered collection of values of type T. Each value has a position called an index. Dart indexes lists from 0, so the first item is at index 0.
Creating and reading lists
Use a list literal when you know the initial values. Dart can infer the element type, or you can write it explicitly.
void main() {
final fruits = <String>['apple', 'banana', 'cherry'];
final numbers = <int>[10, 20, 30];
print(fruits[0]); // apple
print(fruits.length); // 3
print(fruits.last); // cherry
}The final keyword prevents assigning a different list to the variable. It does not make the list's contents immutable. You can still add, remove, or replace elements when the list is growable.
Valid indexes range from 0 through length - 1. Reading fruits[3] in the example above throws a RangeError, because index 3 does not exist.
| Operation | Example | Result |
|---|---|---|
| Read by index | `fruits[1]` | The item at position 1 |
| Get size | `fruits.length` | Number of items |
| Read first item | `fruits.first` | The first item |
| Read last item | `fruits.last` | The last item |
Adding, changing, and removing items
A growable list can change its length. Use add to append an item and insert to place one at a particular index. Assigning to an existing index replaces that item.
void main() {
final fruits = <String>['apple', 'banana'];
fruits.add('cherry');
fruits.insert(0, 'apricot');
fruits[2] = 'blueberry';
print(fruits); // [apricot, apple, blueberry, cherry]
fruits.removeAt(1);
fruits.remove('cherry');
print(fruits); // [apricot, blueberry]
}remove(value) removes the first matching value and returns true if it found one. removeAt(index) removes the item at that position and shifts later items left. Because shifting changes indexes, avoid relying on old indexes after a removal.
For several items, use addAll or insertAll. removeWhere removes every item that satisfies a test.
void main() {
final scores = <int>[40, 75, 20, 90];
scores.addAll([60, 85]);
scores.removeWhere((score) => score < 50);
print(scores); // [75, 90, 60, 85]
}Understanding the list model
Think of a list as numbered storage locations. Reading uses an index. Adding at the end extends the list. Inserting or removing in the middle moves neighboring values.
When you only need to inspect every value, use for-in rather than indexes:
void main() {
final fruits = ['apple', 'banana', 'cherry'];
for (final fruit in fruits) {
print(fruit);
}
}This avoids accidental out-of-range indexes and makes the intent clear.
Exercise
What does items contain after this code runs? final items = <int>[2, 4]; items.insert(1, 3); items.add(5); items.removeAt(0);
Show answer
[3, 4, 5]. The insertion creates [2, 3, 4], add creates [2, 3, 4, 5], and removing index 0 leaves [3, 4, 5].