Learn Dart ยท 3/12

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).

dart
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:

dart
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.

dart
// 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).

dart
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..."

dart
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, prefer for-in loops. Why? Because for-in works better with await (async code) and allows you to use break/continue. forEach does 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.

dart
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.

dart
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.

dart
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.

dart
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

  1. Prefer for-in over standard for: Unless you specifically need the index number (0, 1, 2...), use for-in. It's cleaner and harder to mess up.
  2. 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).
  3. Avoid Infinite Loops: Always ensure your while loop has a way to become false. Otherwise, your app will freeze and your phone might get hot enough to fry an egg ๐Ÿณ.
  4. Exhaustiveness Checking: When using switch with enums, 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:

  1. initialBalance (a double)
  2. transactions (a List<Map<String, dynamic>>)

Each Map in the transactions list represents a single transaction and has the following keys:

  • 'type': A String which can be 'deposit', 'withdrawal', 'fee', or 'interest'.
  • 'amount': A double representing the transaction amount.
  • 'status': A String which can be 'pending', 'completed', or 'failed'.

Your function must adhere to the following processing rules:

  1. Start with the initialBalance.
  2. Iterate through each transaction in the list using a for-in loop.
  3. Use a continue statement to skip any transaction with a 'status' of 'pending'.
  4. Use a break statement to immediately stop all processing if you encounter a transaction with a 'status' of 'failed' that is also a 'withdrawal' with an 'amount' greater than 500.0.
  5. 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.
  6. 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:

dart
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:

  1. Start with currentBalance = 1000.0.
  2. Process the first transaction: {'type': 'deposit', 'amount': 200.0, 'status': 'completed'}. It's 'completed', so the switch expression returns +200.0. currentBalance becomes 1200.0.
  3. Process the second transaction: {'type': 'withdrawal', 'amount': 50.0, 'status': 'completed'}. It's 'completed', so the switch returns -50.0. currentBalance becomes 1150.0.
  4. Process the third transaction: {'type': 'fee', 'amount': 5.0, 'status': 'pending'}. The status is 'pending', so the continue statement is executed, and the rest of the loop body for this iteration is skipped.
  5. Process the fourth transaction: {'type': 'withdrawal', 'amount': 600.0, 'status': 'failed'}. The conditions for the break statement are met (status is 'failed', type is 'withdrawal', and amount > 500.0). The break statement is executed, terminating the loop immediately.
  6. The loop ends. The function returns the final value of currentBalance, which is 1150.0.
dart

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.