In Dart, break
and continue
are powerful flow control statements used within loops. They allow developers to alter the normal execution of loops, providing greater flexibility in program design.
The break
statement is used to exit a loop prematurely. When encountered, it immediately terminates the loop's execution and transfers control to the next statement after the loop.
for (int i = 0; i < 10; i++) {
if (i == 5) {
break;
}
print(i);
}
print('Loop ended');
In this example, the loop will print numbers from 0 to 4, then exit when i
equals 5, skipping the remaining iterations.
continue
is used to skip the rest of the current iteration and move to the next one. It's particularly useful when you want to bypass certain loop iterations based on specific conditions.
for (int i = 0; i < 5; i++) {
if (i == 2) {
continue;
}
print('Number: $i');
}
This code will print all numbers from 0 to 4, except for 2, which is skipped due to the continue
statement.
break
when you need to exit a loop completely based on a condition.continue
to skip specific iterations without terminating the entire loop.break
and continue
affect only the innermost loop unless specified otherwise.To further enhance your understanding of loop control in Dart, explore these related topics:
Mastering break
and continue
statements is crucial for writing efficient and flexible Dart code. These tools allow for more nuanced control over loop execution, enabling developers to create more sophisticated program flows.