How do you write a switch expression in Dart?

← Dart answers

In Dart 3, final result = switch (value) { pattern => result, _ => fallback }; evaluates to a value, and the compiler checks that every case is covered.

String describe(int n) => switch (n) {
  0 => 'zero',
  1 || 2 || 3 => 'few',
  > 3 && < 10 => 'several',
  _ => 'many',
};
 
sealed class Shape {}
class Circle extends Shape { final double r; Circle(this.r); }
class Square extends Shape { final double side; Square(this.side); }
 
double area(Shape s) => switch (s) {
  Circle(:final r) => 3.14159 * r * r,
  Square(:final side) => side * side,
};   // no default needed: all subtypes covered
 
final label = switch (user) {
  User(age: final a) when a < 18 => 'minor',
  _ => 'adult',
};

Cases are checked in order, there is no fall-through, and a sealed base class lets the compiler tell you when a new subtype is not handled. Switch expressions need Dart 3.0 or newer.

Related questions

Start debugging smarter today

Try Bugsee for free — no commitments, no hidden fees.

Free sign upLive demoNo credit card required