Dart Break and Continue
Dart Break
The break statement stops a loop at once.
Dart then goes on with the code after the loop.
This example stops the loop when i is equal to 4:
Example
void main() {
for (var i = 0; i < 10; i++) {
if (i == 4) {
break;
}
print(i);
}
print('The loop is over');
}
Try it Yourself »
Result:
0
1
2
3
The loop is over
A common use of break is to stop searching when you have found what you are looking for:
Example
void main() {
final fruits = ['apple', 'banana', 'cherry', 'kiwi', 'mango'];
for (final fruit in fruits) {
print('Checking $fruit');
if (fruit == 'cherry') {
print('Found it!');
break;
}
}
}
Try it Yourself »
Result:
Checking apple
Checking banana
Checking cherry
Found it!
Dart Continue
The continue statement skips the rest of the current run of the loop.
The loop then goes on with the next run.
This example skips the value 4:
Example
void main() {
for (var i = 0; i < 7; i++) {
if (i == 4) {
continue;
}
print(i);
}
}
Try it Yourself »
Result:
0
1
2
3
5
6
This example prints only the odd numbers, by skipping every even number:
Example
void main() {
for (var i = 1; i <= 9; i++) {
if (i % 2 == 0) {
continue;
}
print(i);
}
}
Try it Yourself »
Result:
1
3
5
7
9
Break and Continue in While Loops
You can also use break and continue in while loops.
Here break stops a loop whose condition is always true:
Example
void main() {
var tries = 0;
while (true) {
tries++;
print('Try number $tries');
if (tries == 3) {
break;
}
}
print('Stopped after $tries tries');
}
Try it Yourself »
Result:
Try number 1
Try number 2
Try number 3
Stopped after 3 tries
When you use continue in a while loop, change the counter before continue.
If you do not, the counter never changes, and the loop never ends:
Example
void main() {
var i = 0;
while (i < 6) {
i++;
if (i == 3) {
continue;
}
print(i);
}
}
Try it Yourself »
Result:
1
2
4
5
6
Break in Nested Loops
In a nested loop, break only stops the inner loop.
The outer loop goes on:
Example
void main() {
for (var i = 1; i <= 3; i++) {
for (var j = 1; j <= 3; j++) {
if (j == 2) {
break;
}
print('i = $i, j = $j');
}
}
}
Try it Yourself »
Result:
i = 1, j = 1
i = 2, j = 1
i = 3, j = 1
To stop the outer loop from inside the inner loop, give the outer loop a label.
A label is a name followed by a colon :, written just before the loop.
Then write break with the label name:
Example
void main() {
outer:
for (var i = 1; i <= 3; i++) {
for (var j = 1; j <= 3; j++) {
if (j == 2) {
break outer;
}
print('i = $i, j = $j');
}
}
print('Both loops are over');
}
Try it Yourself »
Result:
i = 1, j = 1
Both loops are over