Syntax
Type matching occurs in three primary syntactic forms:Mechanics
1. Runtime Type Check
The pattern evaluates the matched value against the specified<Type>. This is functionally equivalent to the expression value is <Type>.
- Annotated Patterns:
int ichecks if the value is anint. - Object Patterns:
Square(area: var a)first checks if the value is aSquarebefore attempting to access theareagetter.
2. Auto-Casting
If the type check succeeds, the value is automatically cast to<Type>. This ensures that subsequent operations within the pattern’s scope (or subpatterns within an Object Pattern) treat the value as the specific type.
3. Binding vs. Discarding
- Variable Pattern: The cast value is assigned to the new variable, scoped to the control flow structure.
- Wildcard Pattern: The type is validated, but the result is discarded.
- Object Pattern: The value is cast to allow extraction of fields defined on that type.
Examples
Variable and Wildcard Patterns
These patterns use explicit annotations to enforce type constraints.Object Pattern
The Object Pattern implicitly performs a type check against the class name provided.Nullability Rules
Type matching strictly enforces nullability.- Non-nullable Type: A pattern
<Type>(e.g.,int) fails if the value isnull. - Nullable Type: A pattern
<Type>?(e.g.,int?) matches if the value is of the specified type ornull.
Generic Types and Reification
When matching against generic types (e.g.,List<int>), the pattern validates the runtime type of the container. Because Dart generics are reified, type arguments are preserved and checked at runtime.
The pattern List<int> list matches only if the object was instantiated as List<int> (or a subtype). It does not inspect the contents of a List<dynamic> to see if they happen to be integers.
Master Dart with Deep Grasping Methodology!Learn More





