as operator is a binary operator used to perform an explicit type cast. It asserts that an object is an instance of a specific type, instructing the compiler to treat the object as that target type while enforcing a runtime check to validate the assertion.
Syntax
Operational Semantics
Theas operator functions as a runtime assertion. When executed, the Dart runtime evaluates the relationship between the runtime type of expression and the TargetType.
- Successful Cast:
If the runtime type of
expressionis a subtype ofTargetType(or exactlyTargetType), the operator returns the object. The static type of the resulting expression becomesTargetType. - Failed Cast:
If the runtime type of
expressionis not a subtype ofTargetType, the operator throws aTypeError. This is an unhandled exception that interrupts execution flow.
Interaction with Null Safety
The behavior of theas operator is strictly governed by Dart’s sound null safety system:
- Casting to Non-Nullable: If
expressionevaluates tonullandTargetTypeis non-nullable (e.g.,String), aTypeErroris thrown immediately becauseNullis not a subtype of the non-nullable type. - Casting to Nullable: If
TargetTypeis nullable (e.g.,String?), castingnullis a valid operation and returnsnull.
Static Analysis
The Dart analyzer evaluatesas expressions at compile-time to identify logical inconsistencies:
- Unnecessary Casts: If the static type of
expressionis already a subtype ofTargetType, the analyzer may flag the cast as redundant. - Impossible Casts: If the static types are disjoint (e.g., casting an expression statically known as
inttoString), the analyzer reports a compile-time error, preventing the code from compiling.
Examples
Successful Cast The following code successfully casts a variable typed asObject to String because the underlying runtime value is a string.
Object can theoretically hold an int, but fails at runtime because the actual value is a String.
null to a non-nullable type triggers an exception because Null is not a subtype of String.
Master Dart with Deep Grasping Methodology!Learn More





