TExcelTAD
Home › Flutter › Dart Control Flow

Dart Control Flow

Programs need to make decisions: show a login screen if the user is signed out, pick a colour depending on a status, and so on. Dart gives you if/else, the conditional operator, and a powerful switch that supports pattern matching since Dart 3.

if, else if and else

The condition in parentheses must be a bool. Blocks in curly braces run only when their condition is true.

dart · try it yourself
void main() {
  var temperature = 24;

  if (temperature > 30) {
    print('Hot day');
  } else if (temperature > 18) {
    print('Pleasant day');
  } else {
    print('Bring a jacket');
  }
}
Pleasant day

Conditions are checked from top to bottom and only the first matching branch runs. For a single short statement the braces are optional, but the Dart style guide recommends them except for very simple one-liners.

Conditional expressions

When you just need to choose a value, the ternary operator is more compact than an if statement:

dart · try it yourself
void main() {
  var battery = 15;
  var icon = battery < 20 ? 'battery_alert' : 'battery_full';
  print(icon);

  // if-case checks a pattern and binds variables (Dart 3)
  Object response = (200, 'OK');
  if (response case (int code, String message) when code == 200) {
    print('Success: $message');
  }
}
battery_alert
Success: OK

if (value case pattern) matches value against a pattern; the optional when clause adds an extra condition. You'll see more patterns below.

switch statements

switch compares one value against several cases. In Dart 3 there is no fall-through: when a case's body ends, the switch is finished — you don't need break.

dart · try it yourself
void main() {
  var command = 'stop';

  switch (command) {
    case 'start':
      print('Starting engine');
    case 'stop':
    case 'halt':
      print('Stopping');
    default:
      print('Unknown command');
  }
}
Stopping

Empty cases (like 'stop' above) share the body of the next case. default (or _) handles anything that didn't match.

switch expressions

A switch expression produces a value. Each case is written pattern => value, separated by commas. This is the modern way to map one value to another.

dart · try it yourself
String describe(int httpStatus) => switch (httpStatus) {
      200 => 'OK',
      301 || 302 => 'Redirect',
      >= 400 && < 500 => 'Client error',
      >= 500 => 'Server error',
      _ => 'Other',
    };

void main() {
  print(describe(200));
  print(describe(302));
  print(describe(404));
  print(describe(503));
  print(describe(100));
}
OK
Redirect
Client error
Server error
Other

Patterns let you match more than constants:

Pattern Matches
200 A constant value
a || b Either pattern
>= 400 Relational comparison
>= 1 && <= 9 Both patterns
int n Any int, bound to n
(x, y) A record with two fields
[a, b, ...] A list starting with two elements
_ Anything (wildcard)

Matching types and shapes

Patterns really shine when you inspect the type or structure of a value:

dart · try it yourself
String classify(Object value) => switch (value) {
      int n when n < 0 => 'negative int $n',
      int n => 'int $n',
      String s when s.isEmpty => 'empty string',
      String s => 'string of length ${s.length}',
      (num x, num y) => 'point at $x, $y',
      [var first, ...] => 'list starting with $first',
      _ => 'something else',
    };

void main() {
  print(classify(-4));
  print(classify(10));
  print(classify(''));
  print(classify('hello'));
  print(classify((1.5, 2)));
  print(classify([9, 8, 7]));
  print(classify(true));
}
negative int -4
int 10
empty string
string of length 5
point at 1.5, 2
list starting with 9
something else

Tip: If you switch over an enum or a sealed class, Dart checks that your cases are exhaustive — forget one and you get a compile error instead of a bug. You'll use this in the Enums and Inheritance lessons.

assert

assert(condition, 'message') stops the program during development if the condition is false. Asserts are removed from release builds, so use them to catch programming mistakes, not to validate user input. Flutter's framework uses asserts heavily to give you helpful error messages in debug mode.

dart
assert(percentage >= 0 && percentage <= 100, 'percentage out of range');

Test yourself

In a Dart 3 switch statement, what happens after a non-empty case body finishes?

  1. It falls through to the next case
  2. The switch ends
  3. A compile error unless you write break
  4. It jumps to default

What does switch (7) { < 5 => 'low', < 10 => 'mid', _ => 'high' } evaluate to?

  1. 'low'
  2. 'mid'
  3. 'high'
  4. null

What does the when keyword add to a case?

  1. A loop
  2. A guard condition that must also be true
  3. A default value
  4. An await