Control Flow
Break and Continue
continue and break change a loop's normal flow. continue skips the rest of the current iteration and resumes at the next condition check (plus the for step if any). break exits the loop immediately, ignoring later iterations entirely. Both are useful for guarding the body's happy path and for bailing out as soon as a stop condition is met.
Program
Play the program to loop over 1..5, continue on 2, break on 5, and keep [1, 3, 4].
break_continue.dart
Replay: real traced execution (multi-file project)
void main() {
var kept = <int>[];
for (var n = 1; n <= 5; n++) {
if (n == 2) continue;
if (n == 5) break;
kept.add(n);
}
var summary = kept.join(',');
print('kept=$summary');
}
kept ← []
1void main() {2 var kept = <int>[];3 for (var n = 1; n <= 5; n++) {values this step[]keptn ← 1
2var kept = <int>[];3for (var n = 1; n <= 5; n++) {4 if (n == 2) continue;values this step1nkept ← [1]
5 if (n == 5) break;6 kept.add(n);7}values this step[] → [1]kept1nn ← 2
2var kept = <int>[];3for (var n = 1; n <= 5; n++) {4 if (n == 2) continue;values this step2ncontinue at ← n == 2
3for (var n = 1; n <= 5; n++) {4 if (n == 2) continue;5 if (n == 5) break;values this stepn == 2continue at2nn ← 3
2var kept = <int>[];3for (var n = 1; n <= 5; n++) {4 if (n == 2) continue;values this step3nkept ← [1, 3]
5 if (n == 5) break;6 kept.add(n);7}values this step[1] → [1, 3]kept3nn ← 4
2var kept = <int>[];3for (var n = 1; n <= 5; n++) {4 if (n == 2) continue;values this step4nkept ← [1, 3, 4]
5 if (n == 5) break;6 kept.add(n);7}values this step[1, 3] → [1, 3, 4]kept4nn ← 5
2var kept = <int>[];3for (var n = 1; n <= 5; n++) {4 if (n == 2) continue;values this step5nbreak at ← n == 5
4if (n == 2) continue;5if (n == 5) break;6kept.add(n);values this stepn == 5break at5nsummary ← 1,3,4
7}8var summary = kept.join(',');9print('kept=$summary');values this step1,3,4summary[1, 3, 4]keptprint('kept=$summary');
8 var summary = kept.join(',');9 print('kept=$summary');10}outputkept=1,3,4values this step1,3,4summary
Skip Two, Stop at Five
keptstarts empty.- The loop visits
1,2,3,4, and5. 2usescontinue, so it is skipped.5usesbreak, so the loop stops.- The program prints
kept=1,3,4. |n| Action | Kept values | | --- | --- | --- | |1| add |1| |2| continue |1| |3| add |1,3| |4| add |1,3,4| |5| break |1,3,4|
continue
`continue` skips the rest of the current iteration and jumps to the next condition check (and the `for` step). The body's later statements are not run for that iteration.
break
`break` exits the loop immediately. No condition check, no increment step, no remaining iterations.
guard before work
Putting `continue`/`break` early keeps the rest of the body as the normal happy path. The loop ran for `n = 1..5` but only added `1, 3, 4` because `2` was skipped and `5` triggered exit.
Exercise: break_continue.dart
Use continue to skip 2, break at 5, and print kept=1,3,4