Control Flow: Making Decisions and Looping
5 min read
๐ Welcome to the Brain of Your Program
Imagine you are a robot butler ๐ค. If you only walked in a straight line and never changed direction, you'd walk straight through a wall!
Control Flow is the logic that tells your code when to stop, where to turn, and how many times to scrub the floor. Without it, your code is just a list of instructions running from top to bottom. With it, your code becomes "intelligent."
1. If-Else Statements and Switch Cases
The Problem: Static Code
You want to buy a video game ๐ฎ. If you have $60, you buy it. If you have less, you cry. Without control flow, your program would try to buy it and cry at the same time.
The Solution: if, else if, else
These keywords let your code "branch" based on a condition (true or false).
void main() {
int wallet = 40;
int gamePrice = 60;
// check condition
if (wallet >= gamePrice) {
print("New game acquired! ๐น๏ธ");
} else if (wallet > 50) {
print("So close! Ask mom for $10? ๐ฅบ");
} else {
// runs if all above are false
print("Time to save up... ๐ท");
}
}Switch Statements: The "Menu" Chooser
When you have one variable and need to check it against many specific values (like a dropdown menu), if-else gets messy. Use switch.
Traditional Switch:
String grade = 'B';
switch (grade) {
case 'A':
print("Outstanding! ๐");
break; // Stops the switch here
case 'B':
print("Good job! ๐");
break;
default: // Runs if nothing matches
print("Keep studying! ๐");
}๐ Industry Pro Tip (Dart 3 Update): Switch Expressions
Since Dart 3, we have a cooler, shorter way to write switches that returns a value directly. This is now widely used in Flutter for things like mapping statuses to colors.
// Modern Dart 3 Syntax โจ
String getEmoji(String weather) {
// Returns the result directly!
return switch (weather) {
'sunny' => '๐',
'rainy' => 'โ',
'snowy' => 'โ๏ธ',
_ => 'โ', // The "_" is the new "default"
};
}2. For Loops and Iteration Basics
The Problem: The "Bart Simpson" Issue
Imagine you need to write "I will not throw chalk" 100 times. Writing print(...) 100 times is a violation of the DRY (Don't Repeat Yourself) principle.
The Solution: for Loops
Loops let you repeat a block of code.
1. Standard C-style For Loop:
Best when you know exactly how many times to run (e.g., indexes).
for (int i = 0; i < 5; i++) {
// i starts at 0, runs while i < 5, increases by 1 each time
print("Iteration number: $i ๐");
}2. For-In Loop (Most Used in Industry ๐):
Best for going through a list of items (like users or products). It reads: "For every player inside the team..."
List<String> heroes = ['Batman', 'Superman', 'Wonder Woman'];
for (var hero in heroes) {
print("$hero is ready for battle! โ๏ธ");
}โ ๏ธ Warning: You might see
.forEach()in older tutorials. In modern Dart, preferfor-inloops. Why? Becausefor-inworks better withawait(async code) and allows you to usebreak/continue.forEachdoes not!
3. While and Do-While Loops
The Problem: Unknown Repetitions
Sometimes you don't know how many times you need to loop. You just want to keep going while a condition is true.
The Solution: while vs do-while
While Loop (The "Check First" Loop):
Checks the condition before running. If the condition is false initially, it never runs.
Analogy: Checking if the pool is warm before jumping in.
int battery = 5;
while (battery > 0) {
print("Phone is on... ๐ $battery%");
battery--; // Decrease battery
}
print("Phone died. ๐");Do-While Loop (The "Do First" Loop):
Runs the code at least once, then checks the condition.
Analogy: Eating a chip first, then deciding if you want more.
int attempts = 0;
do {
print("Trying to connect to Wi-Fi... ๐ถ");
attempts++;
} while (attempts < 3);4. Break and Continue Statements
The Problem: Changing the Plan
Sometimes you are in a loop, but you need to eject immediately (emergency stop) or skip just one annoying step.
Break (The Eject Button โ๏ธ):
Completely stops the loop and exits.
List<String> food = ['Burger', 'Pizza', 'Broccoli', 'Taco'];
for (var item in food) {
if (item == 'Broccoli') {
print("Ew, vegetables! Abort mission! ๐คข");
break; // Stops the loop entirely. Taco is never reached.
}
print("Yum, $item! ๐");
}Continue (The Skip Button โญ๏ธ):
Skips the current iteration and moves to the next one.
for (int i = 1; i <= 5; i++) {
if (i == 3) {
print("Skipping number 3 (it's unlucky) ๐ป");
continue; // Jumps to i = 4 immediately
}
print("Number $i");
}๐ง Industry Standards & Best Practices
- Prefer
for-inover standardfor: Unless you specifically need the index number (0, 1, 2...), usefor-in. It's cleaner and harder to mess up. - Use Switch Expressions: In Flutter apps, using the new Dart 3 switch expression is cleaner for assigning values based on state (e.g.,
Loading,Success,Error). - Avoid Infinite Loops: Always ensure your
whileloop has a way to becomefalse. Otherwise, your app will freeze and your phone might get hot enough to fry an egg ๐ณ. - Exhaustiveness Checking: When using
switchwithenums, Dart checks if you handled every case. This is a huge safety featureโdon't ignore the warnings!
๐ References & Further Reading
Challenge
You are tasked with creating a function to process a list of bank transactions and calculate the final balance.
Implement the function processTransactions which accepts two arguments:
initialBalance(adouble)transactions(aList<Map<String, dynamic>>)
Each Map in the transactions list represents a single transaction and has the following keys:
'type': AStringwhich can be'deposit','withdrawal','fee', or'interest'.'amount': Adoublerepresenting the transaction amount.'status': AStringwhich can be'pending','completed', or'failed'.
Your function must adhere to the following processing rules:
- Start with the
initialBalance. - Iterate through each transaction in the list using a
for-inloop. - Use a
continuestatement to skip any transaction with a'status'of'pending'. - Use a
breakstatement to immediately stop all processing if you encounter a transaction with a'status'of'failed'that is also a'withdrawal'with an'amount'greater than500.0. - For any
'completed'transaction, you must update the balance. Use a Dart 3 switch expression to calculate the change in balance based on the transaction'type':'deposit'and'interest'types are added to the balance.'withdrawal'and'fee'types are subtracted from the balance.
- Finally, return the calculated final balance.
Expected result
Your function should correctly iterate through the list of transactions, applying the specified control flow logic to accurately calculate the final balance.
Example Implementation:
double processTransactions(double initialBalance, List<Map<String, dynamic>> transactions) {
double currentBalance = initialBalance;
for (var transaction in transactions) {
// Rule 3: Skip 'pending' transactions
if (transaction['status'] == 'pending') {
continue;
}
// Rule 4: Break on critical 'failed' transactions
if (transaction['status'] == 'failed' && transaction['type'] == 'withdrawal' && transaction['amount'] > 500.0) {
break;
}
// Rule 5: Process 'completed' transactions
if (transaction['status'] == 'completed') {
double amount = transaction['amount'];
double change = switch (transaction['type']) {
'deposit' || 'interest' => amount,
'withdrawal' || 'fee' => -amount,
_ => 0.0
};
currentBalance += change;
}
}
return currentBalance;
}Logic Explanation:
Given an initial balance of 1000.0 and a specific list of transactions, your code should:
- Start with
currentBalance = 1000.0. - Process the first transaction:
{'type': 'deposit', 'amount': 200.0, 'status': 'completed'}. It's'completed', so theswitchexpression returns+200.0.currentBalancebecomes1200.0. - Process the second transaction:
{'type': 'withdrawal', 'amount': 50.0, 'status': 'completed'}. It's'completed', so theswitchreturns-50.0.currentBalancebecomes1150.0. - Process the third transaction:
{'type': 'fee', 'amount': 5.0, 'status': 'pending'}. The status is'pending', so thecontinuestatement is executed, and the rest of the loop body for this iteration is skipped. - Process the fourth transaction:
{'type': 'withdrawal', 'amount': 600.0, 'status': 'failed'}. The conditions for thebreakstatement are met (statusis'failed',typeis'withdrawal', andamount> 500.0). Thebreakstatement is executed, terminating the loop immediately. - The loop ends. The function returns the final value of
currentBalance, which is1150.0.