Dart While Loop
A while loop repeats a block while its condition stays true. The condition is tested before each run of the block.
Counting with while
The counter grows inside the block after each print. The condition fails at 4 and the loop stops.
void main() {
var i = 1;
while (i <= 3) {
print(i);
i++;
}
}A loop that never runs
The first test is already false. No line from the block reaches the screen, and only the last print shows.
void main() {
var i = 10;
while (i <= 3) {
print(i);
i++;
}
print('After the loop');
}Counting down to a word
The counter drops by one after each print. The word after the loop prints once the condition fails.
void main() {
var i = 3;
while (i >= 1) {
print(i);
i--;
}
print('Start');
}A do while taste
The block runs once before any test happens. The false test then ends the loop after that single run.
void main() {
var i = 10;
do {
print(i);
i++;
} while (i <= 3);
}Example
void main() {
var total = 0;
var i = 1;
while (i <= 4) {
total += i;
i++;
}
print(total);
}Key points
- Use a while loop to repeat a block while a condition is true.
- The condition sits in round brackets after the word while.
- The block must change something, or the loop never ends.
- A false first test means the block never runs.
- Use do while to run the block once before the first test.
In this example, total starts at 0 and the counter starts at 1. Each run adds the counter to total and then grows the counter by one. The runs add 1, 2, 3, and 4 in that order. The condition fails at 5, and the print shows 10.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท DartPad
Exercise
When does a while loop test its condition?