Dart For Loop
Dart For Loop
When you know how many times a loop must run, use the for loop:
for (statement 1; statement 2; statement 3) {
// code block to run
}
- Statement 1 runs one time, before the loop starts
- Statement 2 is the condition, tested before each run of the loop
- Statement 3 runs after each run of the loop
This example prints the numbers 0 to 4:
Result:
0
1
2
3
4
Example Explained
var i = 0creates the variableiand sets it to 0i < 5is the condition, so the loop runs as long asiis less than 5i++adds 1 toiafter each run
The variable i only exists inside the loop.
You can change statement 3 to count in other steps.
This example prints only the even numbers from 0 to 10:
Result:
0
2
4
6
8
10
This example counts down from 5 to 1:
Result:
5
4
3
2
1
A loop can also add up values.
This example adds the numbers 1 to 100:
Example
void main() {
var sum = 0;
for (var i = 1; i <= 100; i++) {
sum += i;
}
print('The sum is $sum');
}
Try it Yourself »
Result:
The sum is 5050
Nested Loops
A loop inside another loop is called a nested loop.
The inner loop runs fully for each run of the outer loop:
Example
void main() {
for (var i = 1; i <= 2; i++) {
print('Outer: $i');
for (var j = 1; j <= 3; j++) {
print(' Inner: $j');
}
}
}
Try it Yourself »
Result:
Outer: 1
Inner: 1
Inner: 2
Inner: 3
Outer: 2
Inner: 1
Inner: 2
Inner: 3
The For-In Loop
A list holds many values in one variable, written in square brackets [].
You will learn more about lists in the Dart Lists chapter.
The for-in loop goes through every item in a list, one by one:
for (final item in list) {
// code block to run
}
Example
void main() {
final cars = ['Volvo', 'BMW', 'Ford', 'Mazda'];
for (final car in cars) {
print(car);
}
}
Try it Yourself »
Result:
Volvo
BMW
Ford
Mazda
The variable car holds a new item each time, so it can be final.
The for-in loop also works with other collections, like sets.
The forEach() Method
Lists also have a forEach() method.
It runs a function for each item in the list:
Example
void main() {
final fruits = ['apple', 'banana', 'cherry'];
fruits.forEach(print);
}
Try it Yourself »
Result:
apple
banana
cherry
Here, print is written without parentheses, so it is not called at once.
Instead, forEach() calls it one time for each item.
You can also write a small function in place, with the item as its parameter:
Example
void main() {
final fruits = ['apple', 'banana', 'cherry'];
fruits.forEach((fruit) {
print('I like $fruit');
});
}
Try it Yourself »
Result:
I like apple
I like banana
I like cherry
You will learn more about functions in the Dart Functions chapter.
Tip: In most cases, the for-in loop is easier to read than forEach().
The Dart style guide also prefers for-in when you write the function in place.