Conditions & Switches

Dart conditional logic with if, else, switch, and expressions.

if / else

var value = 10;

if (value > 10) {
  print('big');
} else if (value <= 10 && value != 0) {
  print('medium');
} else {
  print('small');
}

Ternary operator

var label = value > 5 ? 'big' : 'small';

Null-aware conditional

String? name;
var display = name ?? 'unknown';  // 'unknown' if name is null

switch

Dart switch requires break or other control flow at the end of each case:

var command = 'start';

switch (command) {
  case 'start':
    print('starting');
    break;
  case 'stop':
  case 'quit':
    print('stopping');
    break;
  default:
    print('unknown');
}

Exhaustive switch on enums

enum Status { pending, active, done }

String labelFor(Status status) {
  switch (status) {
    case Status.pending:
      return 'Pending';
    case Status.active:
      return 'Active';
    case Status.done:
      return 'Done';
  }
  // No default needed — compiler knows all cases
}

Switch expressions (Dart 3)

var label = switch (status) {
  Status.pending => 'Pending',
  Status.active => 'Active',
  Status.done => 'Done',
};

Pattern matching (Dart 3)

// Destructuring records
var (name, age) = ('Ada', 30);

// Type patterns in switch
String describe(Object value) {
  switch (value) {
    case int i:
      return 'int: $i';
    case String s:
      return 'string: $s';
    case List<int> list:
      return 'int list of length ${list.length}';
    default:
      return 'unknown';
  }
}

// Guard clauses
switch (value) {
  case int i when i > 0:
    print('positive: $i');
  case int i:
    print('non-positive: $i');
}

Destructuring in for-in loops

var points = [(0, 0), (1, 2), (3, 4)];

for (var (x, y) in points) {
  print('($x, $y)');
}

Next: Collections & Loops