Loops: for and for-in
Prerequisites: Operators
A loop repeats code.
The counting for loop
void main() {
for (var i = 1; i <= 3; i++) {
print('Pass $i');
}
}
Pass 1
Pass 2
Pass 3
The three parts in the parentheses: start (var i = 1), keep going
while (i <= 3), and after each pass (i++).
for-in: loop over a collection
void main() {
final fruits = ['apple', 'banana', 'cherry'];
for (final fruit in fruits) {
print('I like $fruit');
}
for (final (index, fruit) in fruits.indexed) {
print('${index + 1}. $fruit');
}
}
I like apple
I like banana
I like cherry
1. apple
2. banana
3. cherry
indexed pairs each element with its position; (index, fruit) unpacks
both (a record pattern — Level 2 covers records).
Counting down and stepping
void main() {
for (var i = 10; i >= 0; i -= 5) {
print(i);
}
}
10
5
0
forEach
Collections also have a forEach method that takes a function:
void main() {
['a', 'b'].forEach(print);
}
a
b
The style guide prefers for-in loops for most code; forEach is
neat when you already have a function to pass, like print here.
Common mistakes
- Off-by-one errors:
i <= list.lengthgoes one past the end — usei < list.length, or better,for-in.
Practice
Print the 5 times table from 5 x 1 = 5 to 5 x 10 = 50.
Show solution
void main() {
for (var n = 1; n <= 10; n++) {
print('5 x $n = ${5 * n}');
}
}