Skip to main content
The 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

assert(condition);
assert(condition, message);

Parameters

  • condition: An expression that must evaluate to a value of type bool.
  • message: An optional object used to provide context upon failure. If the assertion fails, the AssertionError stores 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 the assert statement is determined by whether assertions are enabled (typically in debug mode) or disabled (typically in production/release mode):
  1. Assertions Enabled: The runtime evaluates the condition.
    • If true: Execution proceeds to the next statement.
    • If false: The runtime throws an AssertionError, interrupting execution.
  2. 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 integrates assert 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 parameter id from int? to int after the assertion.
void process(int? id) {
  // The analyzer assumes execution only continues if id is not null.
  assert(id != null);
  
  // 'id' is promoted to 'int' (local variable promotion).
  // This compiles successfully.
  print(id.isEven); 
}
Note: Because assertions are stripped in production, relying on assert for type promotion implies that the developer guarantees the invariant will hold in the release environment. If id is null in 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