Break and Continue in Dart#
Usage in Loops#
Break Statement to Exit Loops#
About#
The break
statement in Dart is used to exit from a loop immediately, regardless of whether the loop’s condition is still true. It is commonly used when you need to terminate the loop prematurely based on some condition.
How to Use#
- Place the
break
statement inside the loop body. - Typically used in conjunction with an
if
statement to determine when to exit the loop.
How It Works#
- When the
break
statement is executed, the loop stops immediately. - Control is transferred to the statement following the loop.
Example#
void main() {
for (int i = 0; i < 10; i++) {
if (i == 5) {
break; // Exit the loop when i equals 5
}
print(i);
}
}
In this example:#
- The loop iterates from 0 to 9.
- When i equals 5, the break statement is executed, terminating the loop.
- Numbers 0 through 4 are printed before exiting.
- Continue Statement to Skip Iterations
About#
The continue statement in Dart is used to skip the remaining code in the current iteration of a loop and proceed with the next iteration. It is useful when you want to avoid executing certain parts of the loop’s code block based on a condition.
How to Use#
- Place the continue statement inside the loop body.
- Typically used within an if statement to skip over specific iterations.
How It Works#
- When the continue statement is executed, the current iteration of the loop is skipped.
- Control moves to the next iteration of the loop, re-evaluating the loop condition.
Example#
void main() {
for (int i = 0; i < 10; i++) {
if (i % 2 == 0) {
continue; // Skip even numbers
}
print(i);
}
}
In this example:
- The loop iterates from 0 to 9.
- When i is even, the continue statement is executed, skipping the print statement.
- Only odd numbers (1, 3, 5, 7, 9) are printed.
Overall#
The break and continue statements provide control over loop execution in Dart. Use break to exit a loop early based on a condition, and continue to skip specific iterations and proceed with the next one. These statements enhance the flexibility and efficiency of your loop constructs.