TExcelTAD
Home › Dart › Dart If...Else

Dart If...Else

Control flow decides which code runs. Dart has if/else if/else, the conditional operator ? :, the ?? operator and — since Dart 3 — if-case for pattern matching.

if, else if, else

dart · try it yourself
String grade(int score) {
  if (score >= 90) {
    return 'A';
  } else if (score >= 80) {
    return 'B';
  } else if (score >= 65) {
    return 'C';
  } else {
    return 'F';
  }
}

void main() {
  for (final s in [95, 83, 70, 40]) {
    print('$s -> ${grade(s)}');
  }
}
95 -> A
83 -> B
70 -> C
40 -> F

Rules to remember:

  • The condition must be a bool — if (list.length) is a compile error.
  • Braces are optional for a single statement (if (x) print(x);), but use them for anything multi-line. The Dart style guide only allows omitting them when the whole if fits on one line.

The conditional operator

When you need a value rather than an action, use condition ? ifTrue : ifFalse:

dart · try it yourself
void main() {
  var temperature = 31;
  var advice = temperature > 30 ? 'Stay hydrated' : 'Enjoy the weather';
  print(advice);

  var items = 1;
  print('$items ${items == 1 ? 'item' : 'items'}');
}
Stay hydrated
1 item

Avoid nesting ? : more than once — a switch expression is usually clearer (see Switch & Patterns).

Guard clauses

Instead of deeply nested if blocks, handle the exceptional cases first and return early. The "happy path" stays at the left margin:

dart · try it yourself
String checkout(List<String> cart, double balance, double total) {
  if (cart.isEmpty) return 'Cart is empty';
  if (total <= 0) return 'Invalid total';
  if (balance < total) return 'Insufficient funds';

  return 'Paid ${total.toStringAsFixed(2)} for ${cart.length} item(s)';
}

void main() {
  print(checkout([], 100, 10));
  print(checkout(['tea'], 5, 10));
  print(checkout(['tea', 'cake'], 50, 12.5));
}
Cart is empty
Insufficient funds
Paid 12.50 for 2 item(s)

if-case: matching a pattern

Dart 3 added if (value case pattern). The if runs only when the value matches the pattern, and any variables in the pattern are bound inside the block. This is perfect for checking shape and type at once:

dart · try it yourself
void describe(Object? input) {
  if (input case int n when n > 100) {
    print('big number $n');
  } else if (input case int n) {
    print('number $n');
  } else if (input case [String first, ...]) {
    print('list starting with "$first"');
  } else if (input case {'name': String name}) {
    print('map with name $name');
  } else if (input case null) {
    print('nothing');
  } else {
    print('unknown: $input');
  }
}

void main() {
  describe(250);
  describe(7);
  describe(['apple', 'pear']);
  describe({'name': 'Quan', 'age': 30});
  describe(null);
  describe(3.5);
}
big number 250
number 7
list starting with "apple"
map with name Quan
nothing
unknown: 3.5
Part Meaning
case int n Matches if the value is an int, binds it to n
when n > 100 A guard: an extra boolean condition
case [String first, ...] A list whose first element is a String
case {'name': String name} A map that has a String under 'name'

Patterns are covered thoroughly in Patterns & Destructuring.

Assertions

assert(condition, message) checks an assumption during development. Assertions run with dart run --enable-asserts and in Flutter debug mode, but are removed from production builds — never use them for real input validation.

dart
void setVolume(int level) {
  assert(level >= 0 && level <= 10, 'volume out of range: $level');
  // ...
}

Tip: For validation that must always happen, throw an exception: if (level < 0) throw RangeError.range(level, 0, 10);.

Test yourself

What does if (x case int n when n.isEven) do?

  1. Assigns x to n unconditionally
  2. Runs the block only if x is an int and that int is even
  3. Casts x to int and throws otherwise
  4. Compile error — when is not valid here

What is a guard clause?

  1. A try/catch block
  2. An early return that handles an exceptional case first
  3. An assert statement
  4. A private method

Are assert statements executed in production builds?

  1. Always
  2. Never — they are stripped out
  3. Only on the web
  4. Only inside classes