typestar

if, else and the ternary in Dart

Statements branch with if; the ternary picks a value inline.

void main() {
  const cloudCover = 7;
  // Statements branch with if; the ternary picks a value inline.
  final sky = cloudCover > 5 ? 'overcast' : 'clear';
  print('Sky: $sky');

  if (sky == 'clear') {
    print('Swifts hunt high today');
  } else if (cloudCover < 9) {
    print('Watch the low hedges');
  } else {
    print('Herons only');
  }
}

How it works

  1. cond ? a : b is the expression form, feeding a final.
  2. if / else if / else chain for the statement form.
  3. String equality is plain == — no surprises.

Keywords and builtins used here

The run, in numbers

Lines
14
Characters to type
321
Tokens
80
Three-star pace
75 tpm

At the three-star pace of 75 tokens a minute, this run takes about 64 seconds.

Type this snippet

Step 1 of 3 in Control flow, step 4 of 27 in Language basics.

← Previous Next →