Dart Loop Lists
Loop Through a List
The easiest way to go through every item in a list is the for-in loop:
Example
void main() {
final fruits = ['apple', 'banana', 'cherry'];
for (final fruit in fruits) {
print(fruit);
}
}
Try it Yourself »
Result:
apple
banana
cherry
You can do any work with each item inside the loop.
This example adds up all the prices in a list:
Example
void main() {
final prices = [4.5, 12.0, 3.25];
var total = 0.0;
for (final price in prices) {
total += price;
}
print('Total: $total');
}
Try it Yourself »
Result:
Total: 19.75
Loop With the Index
Use a classic for loop when you also need the index of each item.
Start at index 0, and stop before length:
Example
void main() {
final fruits = ['apple', 'banana', 'cherry'];
for (var i = 0; i < fruits.length; i++) {
print('$i: ${fruits[i]}');
}
}
Try it Yourself »
Result:
0: apple
1: banana
2: cherry
With the index, you can also go through the list backwards:
Example
void main() {
final fruits = ['apple', 'banana', 'cherry'];
for (var i = fruits.length - 1; i >= 0; i--) {
print(fruits[i]);
}
}
Try it Yourself »
Result:
cherry
banana
apple
The index also lets you change each item in place:
Example
void main() {
final scores = [10, 20, 30];
for (var i = 0; i < scores.length; i++) {
scores[i] = scores[i] * 2;
}
print(scores);
}
Try it Yourself »
Result:
[20, 40, 60]
The forEach() Method
The forEach() method runs a function for each item in the list:
Example
void main() {
final cars = ['Volvo', 'BMW', 'Ford'];
cars.forEach((car) => print('I drive a $car'));
}
Try it Yourself »
Result:
I drive a Volvo
I drive a BMW
I drive a Ford
The code (car) => print('I drive a $car') is a small function without a name.
It gets one item at a time in car, and the arrow => runs the code after it.
You will learn more in the Dart Arrow Functions chapter.
Loop With asMap()
The asMap() method gives a view of the list as a map, where each index is a key and each item is its value.
With forEach() on that map, you get both the index and the item:
Example
void main() {
final fruits = ['apple', 'banana', 'cherry'];
fruits.asMap().forEach((index, fruit) {
print('$index: $fruit');
});
}
Try it Yourself »
Result:
0: apple
1: banana
2: cherry
You will learn more about maps in the Dart Maps chapter.
Note: Lists also have an indexed property, which gives each item together with its index.
It uses records, which you will learn about in the Dart Records chapter.
Do Not Change the Length in a Loop
You cannot add or remove items while a for-in loop goes through the same list.
Dart throws an error when the program runs:
Example
void main() {
final fruits = ['apple', 'banana', 'cherry'];
for (final fruit in fruits) {
if (fruit == 'banana') {
fruits.add('kiwi');
}
}
}
Try it Yourself »
Result:
Unhandled exception:
Concurrent modification during iteration: Instance(length:4) of '_GrowableList'.
To remove items that match a test, use removeWhere() instead (see Change List Items).