Dart For In Loop
A for in loop runs a block once for each value in a group. The loop name takes each value in turn.
Visiting three numbers
The name n takes 4, then 8, then 15. Each value reaches the screen on its own line.
void main() {
for (var n in [4, 8, 15]) {
print(n);
}
}Visiting pieces of text
The name color takes each word in turn. The words print in the order they sit in the group.
void main() {
for (var color in ['red', 'blue', 'green']) {
print(color);
}
}Working with each value
Each run doubles the current value before printing. The doubled values keep the order of the group.
void main() {
for (var n in [1, 2, 3]) {
print(n * 2);
}
}Example
void main() {
var total = 0;
for (var n in [4, 8, 15]) {
total += n;
}
print(total);
}Key points
- Use a for in loop to visit each value in a group.
- The word in sits between the loop name and the group.
- The loop name holds one value on each run.
- The runs follow the order of the values in the group.
- The block runs once per value, with no counter to manage.
In this example, total starts at 0. The loop visits 4 first and total grows to 4. The loop visits 8 next and total grows to 12. The loop visits 15 last and total grows to 27. The print after the loop shows 27.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท DartPad
Exercise
How many times does the block run in a for in loop?