Skip to main content
A switch statement is a branching control flow construct that evaluates a given expression against a series of case clauses. When a match is found, the statement executes the associated block of code. In Dart 3.0 and later, switch statements fully support pattern matching, allowing for complex destructuring, logical operators, and guard clauses.

Execution Mechanics and Rules

  • Evaluation: The target expression is evaluated exactly once.
  • Matching: Cases are evaluated sequentially from top to bottom. Dart utilizes pattern matching semantics to determine a match. If no patterns match, the default clause (or the wildcard pattern case _:) is executed.
  • Implicit Break (Dart 3.0+): break statements are no longer required at the end of a case block. Dart automatically breaks out of the switch statement after executing a matched, non-empty case.
  • Empty Case Fallthrough: Implicit fallthrough is strictly limited to empty case clauses. If a case has no statements, execution falls through to the next case.

Explicit Fallthrough (Labeled Cases)

To achieve fallthrough across non-empty cases, Dart requires explicit control flow using the continue keyword combined with a label.

Pattern Matching and Logical Operators

Dart allows the use of logical operators (||, &&) and relational operators directly within case clauses to match multiple conditions without relying on empty case fallthrough.

Guard Clauses

A case can be appended with a when keyword followed by a boolean expression. This is known as a guard clause. The case will only match if both the pattern matches the expression and the guard clause evaluates to true.

Exhaustiveness Checking

When switching over algebraic data types—such as enum types, sealed classes, or bool—the Dart analyzer enforces exhaustiveness. The compiler will throw an error if the switch statement does not account for every possible value or subtype, unless a default or wildcard (_) clause is provided.
Tired of Poor Dart Skills? Fix That With Deep Grasping!Learn More