Dart Break & Continue
Control loop execution flow in Dart
🔄 What are Break & Continue?
Break and continue are control statements that help you manage loop execution. Break exits the loop completely, while continue skips the current iteration and moves to the next one.
// Simple break example
for (int i = 1; i <= 5; i++) {
if (i == 3) break;
print(i); // Prints: 1, 2
}
Break vs Continue
Break Statement
Exits the loop completely
for (int i = 1; i <= 5; i++) {
if (i == 3) break;
print(i);
}
Continue Statement
Skips current iteration
for (int i = 1; i <= 5; i++) {
if (i == 3) continue;
print(i);
}
In While Loops
Works with all loop types
int i = 0;
while (i < 5) {
i++;
if (i == 3) continue;
print(i);
}
Nested Loops
Affects innermost loop only
for (int i = 1; i <= 2; i++) {
for (int j = 1; j <= 3; j++) {
if (j == 2) break;
print('$i-$j');
}
}
🔹 Break Statement Examples
Break statement terminates the loop immediately:
void main() {
// Finding first even number
List numbers = [1, 3, 5, 8, 9, 12];
for (int number in numbers) {
if (number % 2 == 0) {
print('First even number: $number');
break; // Exit loop when found
}
}
}
Output:
First even number: 8
🔹 Continue Statement Examples
Continue statement skips the current iteration:
void main() {
// Print only odd numbers
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
continue; // Skip even numbers
}
print('Odd number: $i');
}
}
Output:
Odd number: 1
Odd number: 3
Odd number: 5
Odd number: 7
Odd number: 9
🔹 Practical Examples
Real-world usage of break and continue:
🔸 User Input Validation
void main() {
List inputs = ['abc', '123', 'xyz', '456'];
for (String input in inputs) {
// Skip non-numeric inputs
if (!isNumeric(input)) {
print('Skipping: $input');
continue;
}
int number = int.parse(input);
// Stop if number is too large
if (number > 200) {
print('Number too large, stopping');
break;
}
print('Valid number: $number');
}
}
bool isNumeric(String str) {
return int.tryParse(str) != null;
}
Output:
Skipping: abc
Valid number: 123
Skipping: xyz
Valid number: 456
🔹 Best Practices
When to use Break:
- Search operations: Stop when item is found
- Error conditions: Exit on invalid data
- Performance: Avoid unnecessary iterations
When to use Continue:
- Filtering: Skip unwanted items
- Validation: Skip invalid data
- Conditional processing: Process only specific items