Dart While Loop
Loops
A loop runs the same block of code many times.
Loops save time, and they make code shorter and easier to read.
Dart has these loops:
whileanddo-while, covered in this chapterforandfor-in, covered in the For Loop chapter
Dart While Loop
The while loop repeats a block of code as long as a condition is true:
while (condition) {
// code block to run
}
In this example, the loop runs as long as i is less than 5:
Result:
0
1
2
3
4
This is how it works:
- Dart tests the condition
i < 5before each run of the loop - If the condition is true, Dart runs the code block
i++adds 1 toieach time- When
ibecomes 5, the condition is false and the loop stops
We use var and not final for i, because its value changes.
Note: Do not forget to change the variable that the condition uses.
If the condition never becomes false, the loop never ends.
This is called an infinite loop.
More While Examples
A while loop can count down too:
Example
void main() {
var countdown = 3;
while (countdown > 0) {
print(countdown);
countdown--;
}
print('Happy New Year!');
}
Try it Yourself »
Result:
3
2
1
Happy New Year!
A while loop is useful when you do not know how many times the loop must run.
This example doubles a savings amount until it reaches at least 1000:
Example
void main() {
var savings = 100;
var years = 0;
while (savings < 1000) {
savings = savings * 2;
years++;
}
print('After $years years, the savings are $savings');
}
Try it Yourself »
Result:
After 4 years, the savings are 1600
The Do-While Loop
The do-while loop runs the code block first, and then tests the condition:
do {
// code block to run
} while (condition);
Note the semicolon ; after the condition.
Result:
0
1
2
3
4
While or Do-While?
A do-while loop always runs at least once, even when the condition is false from the start.
Here the condition i < 5 is false, but the code block still runs one time:
Result:
i is 10
A while loop with the same condition does not run at all, so this program prints only "Done":
Example
void main() {
var i = 10;
while (i < 5) {
print('i is $i');
i++;
}
print('Done');
}
Try it Yourself »
Result:
Done
Stop or Skip
To stop a loop early, or to skip one run of a loop, use break and continue.
You will learn about them in the Break and Continue chapter.