assert statement is a syntactic construct used to verify boolean invariants during development. It validates that a specific condition holds true at a specific point in execution, throwing an AssertionError if the condition evaluates to false.
Syntax
Parameters
condition: An expression that must evaluate to a value of typebool.message: An optional object used to provide context upon failure. If the assertion fails, theAssertionErrorstores this object reference directly. The object’s.toString()method is invoked only if the error object itself is converted to a string.
Compilation and Execution Semantics
The behavior of theassert statement is determined by whether assertions are enabled (typically in debug mode) or disabled (typically in production/release mode):
- Assertions Enabled: The runtime evaluates the
condition.- If
true: Execution proceeds to the next statement. - If
false: The runtime throws anAssertionError, interrupting execution.
- If
- Assertions Disabled: The compiler treats the assertion as dead code. The statement and the evaluation of its condition are stripped from the binary, ensuring zero runtime performance cost and preventing binary size inflation.
Interaction with Flow Analysis
The Dart analyzer integratesassert statements into control flow analysis and type promotion. The analyzer assumes that if execution passes an assert statement, the asserted condition is true. Consequently, local variables and parameters checked within an assertion are promoted to more specific types in the subsequent scope.
Instance fields and static variables are not subject to type promotion via assertions, as their values can change between the assertion check and subsequent usage.
Type Promotion Example
In the following example, the analyzer promotes the nullable local parameterid from int? to int after the assertion.
Note: Because assertions are stripped in production, relying onassertfor type promotion implies that the developer guarantees the invariant will hold in the release environment. Ifidisnullin a production build, the guard clause is removed, potentially resulting in a runtime exception when accessing members of the promoted type.
Master Dart with Deep Grasping Methodology!Learn More





