Dart Lesson 18 of 102 3 min read
break and continue in Dart
Use break to leave a loop early and continue to skip one round. Includes labels for controlling nested loops in Dart.
On this page
Sometimes you need to change the flow of a loop from the inside. break stops the loop completely. continue skips the rest of the current round and moves on to the next.
break #
void main() {
var numbers = [4, 9, 15, 22, 8];
for (final n in numbers) {
if (n > 10) {
print('First number over 10 is $n');
break;
}
print('Checked $n');
}
}
Checked 4
Checked 9
First number over 10 is 15
Once the answer is found there is no reason to look at 22 and 8, so break saves the work.
continue #
void main() {
for (var i = 1; i <= 6; i++) {
if (i.isEven) continue; // skip even numbers
print(i);
}
}
1
3
5
break in a while (true) loop #
A loop with the condition true runs until a break. This is a common way to write “keep going until done”.
void main() {
var total = 0;
var n = 1;
while (true) {
total += n;
if (total > 20) break;
n++;
}
print('Stopped at n = $n with total $total');
}
Stopped at n = 6 with total 21
Nested loops and labels #
break and continue only affect the loop they are written in. To control an outer loop, give it a label.
void main() {
outer:
for (var row = 1; row <= 3; row++) {
for (var col = 1; col <= 3; col++) {
if (col == 2 && row == 2) break outer; // leaves both loops
print('row $row, col $col');
}
}
print('Done');
}
row 1, col 1
row 1, col 2
row 1, col 3
row 2, col 1
Done
continue outer; works the same way: it jumps to the next round of the labelled loop.
Labels are rarely needed. If you reach for one, consider moving the loops into a function and using return instead.
A practical example #
void main() {
var entries = ['12', 'abc', '7', '', 'stop', '99'];
var sum = 0;
for (final entry in entries) {
if (entry == 'stop') break; // stop reading
final value = int.tryParse(entry);
if (value == null) continue; // ignore bad input
sum += value;
}
print('Sum: $sum');
}
Sum: 19
Things to remember #
breakandcontinuedo not work insideforEach. Use afor-inloop when you need them.- In a
whileloop, make sure the counter is updated beforecontinue, or the loop will never end. - Since Dart 3 you do not need
breakat the end of aswitchcase.
Try it yourself #
Loop from 1 to 50. Skip every number divisible by 3, and stop completely at the first number divisible by both 5 and 7. Print the numbers you visit.