Control flow operators in Dart enable developers to make decisions, iterate over collections, and handle exceptional situations gracefully.
1. if-else Statements:
The if statement is used for conditional execution. If the condition is true, the block of code inside the if statement is executed.
Optionally, you can include an else block to specify code that should be executed if the condition is false.
void main() {
int number = 10;
if (number > 0) {
print('Number is positive');
} else {
print('Number is non-positive');
}
}
2. switch Statements:
The switch statement is used to conditionally execute code based on the value of an expression.
void main() {
String fruit = 'apple';
switch (fruit) {
case 'apple':
print('It\'s an apple');
break;
case 'banana':
print('It\'s a banana');
break;
default:
print('Unknown fruit');
}
}
3. for Loop:
The for loop is used for iterating a specific number of times.
void main() {
for (int i = 0; i < 5; i++) {
print('Iteration $i');
}
}
4. while Loop:
The while loop continues executing a block of code while a specified condition is true.
void main() {
int count = 0;
while (count < 3) {
print('Count: $count');
count++;
}
}
5. do-while Loop:
Similar to the while loop, but the condition is checked after the loop body is executed, so the body is guaranteed to execute at least once.
void main() {
int count = 0;
do {
print('Count: $count');
count++;
} while (count < 3);
}
6. break and continue:
The break statement is used to exit a loop prematurely, and the continue statement is used to skip the rest of the code inside a loop for the current iteration.
void main() {
for (int i = 0; i < 5; i++) {
if (i == 2) {
break; // Exit the loop when i is 2
}
print('Iteration $i');
}
}
These control flow operators in Dart help you manage the flow of your program, making it flexible and responsive to different conditions.