Dart Access List Items
Access List Items
Each item in a list has a position number, called its index.
The first item has index 0, the second item has index 1, and so on.
To get an item, write the index in square brackets after the list name:
Example
void main() {
final fruits = ['apple', 'banana', 'cherry'];
print(fruits[0]);
print(fruits[2]);
}
Try it Yourself »
Result:
apple
cherry
The last item always has the index length - 1:
Example
void main() {
final fruits = ['apple', 'banana', 'cherry'];
print(fruits[fruits.length - 1]);
}
Try it Yourself »
Result:
cherry
First and Last
The first and last properties give the first and the last item of a list:
Example
void main() {
final cars = ['Volvo', 'BMW', 'Ford', 'Mazda'];
print(cars.first);
print(cars.last);
}
Try it Yourself »
Result:
Volvo
Mazda
Index Out of Range
If you use an index that does not exist in the list, Dart throws a RangeError when the program runs.
This list has 3 items, so the valid indexes are 0, 1 and 2:
Example
void main() {
final fruits = ['apple', 'banana', 'cherry'];
print(fruits[3]);
}
Try it Yourself »
Result:
Unhandled exception:
RangeError (length): Invalid value: Not in inclusive range 0..2: 3
Note: Dart does not support negative indexes like fruits[-1].
Use last to get the last item.
Part of a List
The sublist() method gives a new list with a part of the items.
It takes a start index and an end index.
The item at the start index is included, but the item at the end index is not:
Example
void main() {
final fruits = ['apple', 'banana', 'cherry', 'orange', 'kiwi', 'melon'];
print(fruits.sublist(2, 5));
}
Try it Yourself »
Result:
[cherry, orange, kiwi]
If you leave out the end index, the new list goes to the end of the list:
Example
void main() {
final fruits = ['apple', 'banana', 'cherry', 'orange', 'kiwi', 'melon'];
print(fruits.sublist(3));
}
Try it Yourself »
Result:
[orange, kiwi, melon]
The original list does not change.
Find an Item
The contains() method returns true if the list has the item, and false if it does not:
Example
void main() {
final fruits = ['apple', 'banana', 'cherry'];
if (fruits.contains('apple')) {
print('Yes, apple is in the list');
}
print(fruits.contains('mango'));
}
Try it Yourself »
Result:
Yes, apple is in the list
false
The indexOf() method returns the index of the first matching item.
If the item is not in the list, it returns -1:
Example
void main() {
final fruits = ['apple', 'banana', 'cherry', 'banana'];
print(fruits.indexOf('banana'));
print(fruits.indexOf('mango'));
}
Try it Yourself »
Result:
1
-1
The lastIndexOf() method works the same way, but it searches from the end:
Example
void main() {
final fruits = ['apple', 'banana', 'cherry', 'banana'];
print(fruits.lastIndexOf('banana'));
}
Try it Yourself »
Result:
3