Dart Control Flow

Managing program execution flow in Dart

🔄 What is Control Flow?

Control flow determines the order in which code executes. Dart provides various statements like if-else, loops, and switch to control program execution based on conditions and repetition needs.


// Simple control flow example
void main() {
  int age = 18;
  if (age >= 18) {
    print('You are an adult');
  } else {
    print('You are a minor');
  }
}
                                    

Types of Control Flow

🤔

Conditional Statements

Execute code based on conditions

if-else switch ternary
🔁

Loop Statements

Repeat code multiple times

for while do-while
🚪

Jump Statements

Control loop execution

break continue return

Exception Handling

Handle errors gracefully

try-catch finally throw

🔹 Basic Control Flow Example

Here's a simple program demonstrating different control flow statements:

void main() {
  // Conditional statement
  int score = 85;
  if (score >= 90) {
    print('Grade: A');
  } else if (score >= 80) {
    print('Grade: B');
  } else {
    print('Grade: C');
  }
  
  // Loop statement
  for (int i = 1; i <= 3; i++) {
    print('Count: $i');
  }
}

Output:

Grade: B

Count: 1

Count: 2

Count: 3

🔹 Control Flow Best Practices

Follow these guidelines for clean control flow:

Good Practices:

  • Use meaningful conditions: Make your if statements clear
  • Avoid deep nesting: Keep code readable with early returns
  • Choose appropriate loops: Use for, while, or do-while based on needs
  • Handle edge cases: Consider all possible scenarios
// Good: Clear and readable
void checkAge(int age) {
  if (age < 0) {
    print('Invalid age');
    return;
  }
  
  if (age >= 18) {
    print('Adult');
  } else {
    print('Minor');
  }
}

🧠 Test Your Knowledge

Which statement is used to exit a loop early?