2. Mastering Control Flow in Dart: Making Decisions and Iterating Efficiently
1. Conditional Branching with if and else
Dart uses if and else statements for branching logic. These constructs allow developers to execute code conditionally, based on boolean expressions.
Syntax:
if (condition) {
// Code to execute if condition is true
} else if (anotherCondition) {
// Code to execute if anotherCondition is true
} else {
// Code to execute if none of the conditions are true
}
Example:
int age = 20;
if (age >= 18) {
print("You are an adult.");
} else {
print("You are not an adult.");
}
Best Practices:
Use
else iffor multiple conditions to avoid deeply nestedifblocks.Use boolean expressions directly for clarity (e.g.,
if (isValid)instead ofif (isValid == true)).
2. Multi-way Branching with switch and case
When dealing with multiple possible values for a single variable, switch and case provide a cleaner alternative to multiple if-else statements.
Syntax:
switch (variable) {
case value1:
// Code to execute for value1
break;
case value2:
// Code to execute for value2
break;
default:
// Code to execute if no case matches
break;
}
Example:
String day = "Monday";
switch (day) {
case "Monday":
print("Start of the workweek.");
break;
case "Friday":
print("Almost the weekend!");
break;
default:
print("It's a regular day.");
break;
}
Key Points:
Always include a
breakstatement to prevent fall-through to the next case.Use the
defaultcase to handle unexpected values.
3. Iteration with Loops
Dart provides several types of loops for executing repetitive logic efficiently.
for Loop
The for loop is used when the number of iterations is known in advance.
for (int i = 0; i < 5; i++) {
print("Iteration $i");
}
for-in Loop
The for-in loop is ideal for iterating over collections like lists, sets, or maps.
List<String> fruits = ["Apple", "Banana", "Cherry"];
for (var fruit in fruits) {
print("I love $fruit");
}
while Loop
The while loop executes as long as a condition is true.
int count = 0;
while (count < 3) {
print("Count is $count");
count++;
}
do-while Loop
The do-while loop ensures that the code block runs at least once before the condition is checked.
int num = 1;
do {
print("Number is $num");
num++;
} while (num <= 3);
4. Keywords for Enhanced Control
break
The break keyword is used to exit a loop or switch statement prematurely.
for (int i = 0; i < 10; i++) {
if (i == 5) {
break; // Exit the loop when i is 5
}
print(i);
}
continue
The continue keyword skips the current iteration and moves to the next one.
for (int i = 0; i < 10; i++) {
if (i % 2 != 0) {
continue; // Skip odd numbers
}
print(i); // Prints only even numbers
}
5. Logical Operators in Control Flow
Dart supports logical operators to create compound conditions:
&&: Logical AND (true if both conditions are true).||: Logical OR (true if at least one condition is true).!: Logical NOT (inverts the condition).
Example:
bool isMember = true;
int age = 25;
if (isMember && age >= 18) {
print("Eligible for membership benefits.");
} else {
print("Not eligible.");
}
6. Practical Use Cases and Insights
Nested Loops with Conditions
Nested loops combined with conditions are useful for working with multi-dimensional data like grids or matrices.
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
print("Position: ($i, $j)");
}
}
Real-world Scenario: Input Validation
String password = "12345";
if (password.length < 6) {
print("Password must be at least 6 characters long.");
} else if (!password.contains(RegExp(r'[A-Z]'))) {
print("Password must include an uppercase letter.");
} else {
print("Password is valid.");
}
7. Best Practices for Control Flow in Dart
Keep it Simple: Avoid overly complex conditions; break them into smaller, readable parts.
Minimize Side Effects: Ensure conditions don’t unintentionally alter variable states.
Use Descriptive Variables: Use meaningful names for loop counters and condition variables.
Prefer
for-infor Collections: When iterating over lists or sets, usefor-infor concise and readable code.