DT Dart

Dart: Control Flow

What you will learn

Conditionals, loops, and the for-in loop that Dart uses to iterate over collections.

if / else if / else

int score = 85;
if (score >= 90) {
  print('A');
} else if (score >= 80) {
  print('B');
} else {
  print('F');
}

Conditions must be boolean expressions — no truthy/falsy coercion (unlike JavaScript).

Loops

Traditional for loop

for (int i = 0; i < 5; i++) {
  print(i);  // 0 1 2 3 4
}

For-in loop (iterate over iterables)

var items = [1, 2, 3];
for (var item in items) {
  print(item);
}

While loop

int i = 0;
while (i < 3) {
  print(i);
  i++;
}

Switch expression (Dart 3+)

Modern Dart uses switch as an expression that returns a value:

String day = 'Monday';
String type = switch (day) {
  'Saturday' || 'Sunday' => 'Weekend',
  _ => 'Weekday'
};
print(type);  // Weekday

The print() function

Dart uses print() to output to the console. String interpolation with $ works inside strings:

var name = 'Alice';
print('Hello, $name!');  // Hello, Alice!

Common mistakes

  • Using expressions that are not boolean in if conditions — Dart does not auto-coerce null or 0 to false
  • Forgetting semicolons after statements — Dart requires them (unlike JavaScript)
  • Using == for reference equality on objects — override == or use identical()

Quick check below!