switch statements and switch expressions that qualifies a pattern match with a boolean predicate. The guard, denoted by the when keyword, requires that the condition evaluate to true for the case to be selected, even if the pattern matches the value’s structure and type.
Syntax
The guard clause immediately follows the pattern and precedes the case body or expression arrow. In aswitch statement:
switch expression:
Evaluation Semantics
The runtime evaluates a guarded pattern in a strict sequence:- Pattern Matching: The subject value is tested against the pattern’s structure and type.
- Variable Binding: If the pattern matches, any variables defined within the pattern are destructured and bound.
- Guard Evaluation: The boolean expression in the
whenclause is evaluated.- Scope: Variables bound in step 2 are accessible within the guard expression.
- Result Determination:
- If the guard evaluates to
true, the match succeeds, and the corresponding body executes. - If the guard evaluates to
false, the match is refuted. The execution flow proceeds to the nextcaseordefaultclause.
- If the guard evaluates to
Valid Contexts
Guarded patterns are supported only inswitch contexts. They are not valid in if-case statements, for-case loops, or variable declarations.
Switch Statement
The guard acts as a filter for the case block.Switch Expression
Guards allow a single pattern structure to map to different result expressions based on value constraints.Refutation and Fallthrough
A guard failure is distinct from a boolean check inside a case body. If a guard evaluates tofalse, the switch statement does not terminate; instead, it treats the specific case as a non-match and continues evaluating subsequent cases.
Master Dart with Deep Grasping Methodology!Learn More





