Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 61 ยท Control Flow

switch Statements and Expressions

Learn Dart 3 switch: statements without fall-through, switch expressions, exhaustiveness checks for enums and sealed classes, and guard clauses with when.

A switch chooses between many branches based on one value. Dart 3 turned it from a plain jump table into something much more capable: cases are patterns, a switch can be an expression that produces a value, and the compiler can check that you covered every possibility.

This lesson shows the two forms of switch, how exhaustiveness works, and how guard clauses refine a case. The Dart code is read-only; the TypeScript stand-ins let you run the same logic.

The switch statement

A switch statement compares a value against a list of cases and runs the body of the first one that matches.

DART
void describe(int day) {
  switch (day) {
    case 1:
      print('Monday');
    case 6:
    case 7:
      print('Weekend');
    default:
      print('Another weekday');
  }
}

Two things differ from C, Java or JavaScript:

  • No fall-through. When a case body ends, the switch ends. You do not write break (you may, but it is not needed).
  • Empty cases stack. case 6: has no body, so it shares the body of case 7:. That is the only kind of sharing allowed. You can also write it as one case with an or-pattern: case 6 || 7:.

If you really want to jump to another case, use continue with a label:

DART
void demo(int n) {
  switch (n) {
    case 1:
      print('one');
      continue two;
    two:
    case 2:
      print('two');
  }
}

That is rare. Most code never needs it.

TypeScript A switch statement (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The value can be any type that supports the case patterns you write: integers, strings, enums, records, objects. Dart constant patterns compare with ==, so strings match by content:

DART
String reply(String command) {
  switch (command) {
    case 'start':
      return 'Starting';
    case 'stop':
      return 'Stopping';
    default:
      return 'Unknown command: $command';
  }
}

The switch expression

When every branch only computes a value, a switch expression is shorter. It uses => and commas instead of case, colons and return:

DART
String dayType(int day) => switch (day) {
      1 || 2 || 3 || 4 || 5 => 'Weekday',
      6 || 7 => 'Weekend',
      _ => 'Not a day',
    };

The pieces:

  • switch (day) { ... } appears where a value is needed, here after =>.
  • Each arm is pattern => result, separated by commas. A trailing comma is allowed.
  • _ is the wildcard pattern and acts like default: it matches anything.
  • The first matching arm wins, and the whole expression has the value of that arm.

You can assign the result, pass it to a function or return it:

DART
void main() {
  final temperature = 31;
  final label = switch (temperature) {
    < 0 => 'freezing',
    < 15 => 'cold',
    < 25 => 'mild',
    _ => 'hot',
  };
  print(label); // hot
}

< 0 is a relational pattern: it matches when the value compares as specified. Arms are tried from top to bottom, so order matters. Putting < 25 before < 15 would hide the colder arm.

TypeScript A switch expression with ranges (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

flowchart TD
    V["Value to test"] --> A1{"Arm 1 matches?"}
    A1 -->|"yes"| R1["Result 1"]
    A1 -->|"no"| A2{"Arm 2 matches?"}
    A2 -->|"yes"| R2["Result 2"]
    A2 -->|"no"| A3{"Wildcard _"}
    A3 --> R3["Default result"]

Arms are tested from top to bottom; the first match decides the result.

Exhaustiveness

A switch expression must produce a value for every possible input. If the compiler cannot prove that your arms cover everything, it reports an error. Dart does this check for:

  • bool (needs true and false),
  • enums (every value),
  • sealed class hierarchies (every subtype),
  • nullable versions of those (also null),
  • and records and patterns built from them.

With an enum:

DART
enum Light { red, yellow, green }

String action(Light light) => switch (light) {
      Light.red => 'Stop',
      Light.yellow => 'Slow down',
      Light.green => 'Go',
    };

No wildcard is needed, and that is on purpose. If you later add Light.flashing to the enum, this switch stops compiling until you handle the new case. A _ arm would silence that warning and hide the bug, so avoid it for enums and sealed types. Switch statements over these types are checked the same way since Dart 3.

An int or String has too many values to list, so you always need a wildcard or default arm for them.

The sealed pattern, which makes this especially powerful, is explained in Class modifiers. Enums are covered in Enums.

Leave out the wildcard when you switch over an enum or a sealed type. The compiler then tells you every place to update when the type grows.

TypeScript Exhaustive handling with a union type (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Guards with when

Sometimes the pattern alone is not precise enough. A guard clause adds a condition after the pattern with when. The case matches only when both the pattern and the guard succeed.

DART
String classify(int n) => switch (n) {
      0 => 'zero',
      int x when x < 0 => 'negative',
      int x when x.isEven => 'positive and even',
      _ => 'positive and odd',
    };

int x is a variable pattern with a type: it matches an int and binds it to x, which you can then use in the guard and in the result. Guards work in switch statements too:

DART
void check(Object value) {
  switch (value) {
    case int n when n > 100:
      print('big number');
    case int n:
      print('number $n');
    case String s when s.isEmpty:
      print('empty string');
    case String s:
      print('string "$s"');
    default:
      print('something else');
  }
}

Order again matters: int n when n > 100 must come before the plain int n. If the guard is false, Dart moves on to the next case. A guarded case does not count towards exhaustiveness, because the guard might fail, so you still need an unguarded arm that covers the same type.

TypeScript Guards in action (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Statement or expression?

Choose the statement when the branches do things, such as printing, assigning several variables or calling functions with side effects. Choose the expression when every branch simply produces one value. An expression cannot contain statements in its arms, but an arm can call a function if you need to do more work. The full range of patterns (lists, maps, records and objects) comes next in Patterns and destructuring.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What happens at the end of a case body in a Dart 3 switch statement?

    Dart cases do not fall through. Only empty cases share the body of the case below them.
  2. 2. What does the arm _ => 'other' do in a switch expression?

    The underscore is the wildcard pattern. It matches everything, so it works as a catch-all arm.
  3. 3. Why is it better to omit the wildcard when switching over an enum?

    Exhaustiveness checking works only when every value is listed. A wildcard would hide a newly added value.
  4. 4. In case int n when n > 100:, what is when n > 100?

    The case matches only when the pattern matches and the guard evaluates to true. Otherwise Dart tries the next case.

Summary

  • Switch statements have no fall-through; empty cases can be stacked or combined with ||.
  • A switch expression uses pattern => value, arms and returns a value; _ matches anything.
  • Arms are tried in order, so put specific ones before general ones.
  • Enums, bool and sealed types are checked for exhaustiveness; skip the wildcard to benefit from it.
  • when adds a guard condition to a case, and the bound variable can be used in it.

Next: patterns and destructuring.