Dart Break and Continue
The break command ends a loop at once. The continue command skips the rest of one run and moves to the next run.
Breaking out of a loop
The loop counts toward 5, but break fires at 3. Only the numbers 1 and 2 reach the screen.
void main() {
for (var i = 1; i <= 5; i++) {
if (i == 3) {
break;
}
print(i);
}
}Skipping one run
The continue line fires at 3, so that run prints nothing. The other runs print as normal.
void main() {
for (var i = 1; i <= 5; i++) {
if (i == 3) {
continue;
}
print(i);
}
}Breaking out of a for in loop
The loop visits values in order and break fires at 15. The value 16 never reaches the screen.
void main() {
for (var n in [4, 8, 15, 16]) {
if (n == 15) {
break;
}
print(n);
}
}Code after a break
The break ends the loop at 2. The print below the loop still runs after the break.
void main() {
for (var i = 1; i <= 5; i++) {
if (i == 2) {
break;
}
print(i);
}
print('Loop ended');
}Example
void main() {
for (var i = 1; i <= 6; i++) {
if (i == 2 || i == 4) {
continue;
}
print(i);
}
}Key points
- Use break to leave a loop before its normal end.
- Use continue to skip the rest of the current run.
- After continue, the loop moves on to its next run.
- After break, the code below the loop runs next.
- Both commands often sit inside an if block in the loop.
In this example, the counter runs from 1 to 6. The if test catches the counter at 2 and at 4. The continue command skips the print on those two runs. The other runs print 1, 3, 5, and 6.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท DartPad
Exercise
What does continue do inside a loop?