switch construct evaluates a governing expression against a series of patterns to determine control flow or compute a result. It supports both statement syntax for imperative control flow and expression syntax for functional value assignment.
Switch Statements
A switch statement executes the block of code associated with the first matching pattern.Pattern Matching Logic
case clauses utilize pattern matching to validate the governing expression. The matching logic depends on the pattern type:
- Constant Patterns: Compare the governing expression to a constant (e.g.,
case 1:,case 'A':) using the==operator. - Relational Patterns: Compare values using operators (e.g.,
case > 10:). - Object and List Patterns: Validate structure and types, allowing for destructuring (e.g.,
case [int a, int b]:). - Logical Patterns: Combine multiple patterns using logical operators (e.g.,
case 200 || 201:).
Guard Clauses
Acase clause may include an optional guard clause using the when keyword. The case matches only if the pattern matches the value and the guard expression evaluates to true.
Control Flow Rules
Dart enforces specific rules regarding how execution moves through switch statements:- Implicit Break: Non-empty
caseclauses automatically break at the end of their block. Explicitbreakstatements are optional and generally unnecessary unless exiting a case early. - No Fall-through for Non-empty Cases: If a
casebody contains statements, execution does not fall through to the next case. - Fall-through for Empty Cases: Dart allows fall-through only for empty
caseclauses, allowing multiple patterns to share the same body.
- Labels and Continue: To explicitly transfer control from one non-empty case to another, use a label and the
continuestatement.
Switch Expressions
Dart supportsswitch as an expression, producing a value directly. This syntax uses the arrow (=>) instead of the colon (:) and case keyword. Unlike statements, switch expressions require commas separating the cases.
Exhaustiveness Checking
Dart enforces exhaustiveness checking for both switch statements and expressions when the governing expression’s type is “exhaustible” (e.g.,enum, bool, or sealed classes).
- Requirement: Every possible value of the exhaustible type must be covered by a case.
- Enforcement: Missing a case for a known value in an exhaustible type results in a compile-time error.
- Wildcards: The wildcard pattern (
_) or adefaultclause can be used to cover remaining cases for non-exhaustible types (likeintorString) or to handle future additions to an enum.
sealed class hierarchy, direct subtypes must be declared base, final, or sealed.
Master Dart with Deep Grasping Methodology!Learn More





