A cast pattern in Dart allows you to assert the type of a matched value during pattern matching and destructuring. It uses theDocumentation Index
Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
Use this file to discover all available pages before exploring further.
as keyword to perform a downcast, throwing a TypeError at runtime if the matched value does not conform to the specified type, rather than silently failing the match.
Syntax
as keyword and a type annotation.
Mechanics
During runtime execution, a cast pattern evaluates an incoming value through the following strict sequence:- Casting: The Dart runtime applies the
as <type>operation to the incoming value first. If the value is not of the specified<type>, aTypeErroris thrown immediately, halting the pattern match. - Matching: If the cast succeeds, the runtime then evaluates the newly cast value against the inner
<pattern>. - Binding: If the inner pattern is a variable pattern, the variable is bound with the static type defined by
<type>.
as operator, a cast pattern does not alter the control flow by rejecting a match if the type is incorrect. Instead, an invalid type assertion results in an unhandled runtime exception.
Syntax Visualization
In Variable Declarations (Destructuring):Cast Pattern vs. Safe Type Matching
It is critical to distinguish the cast pattern (as) from patterns that safely test types without throwing exceptions, such as typed wildcard patterns or typed variable patterns.
- Typed Wildcard Pattern (
<type> _): Acts as a guard. If the value is not of the specified type, the pattern match fails, and execution proceeds to the next case. It tests the type without binding the value to a variable. - Typed Variable Pattern (
<type> <name>): Declares a variable with a type annotation. It also acts as a guard, failing gracefully if the type does not match, but binds the value to a variable if successful. - Cast Pattern (
<pattern> as <type>): Acts as an assertion. It assumes the match is valid and forces the type evaluation first. If the value is not of the specified type, the program throws aTypeError.
case String:) to test a type. This creates a Constant Pattern that matches the Type object itself, not instances of that type.
Master Dart with Deep Grasping Methodology!Learn More





