Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

The null-assert pattern (!) is a unary pattern that matches a value, asserts that the value is not null, and casts it to its underlying non-null type. If the matched value evaluates to null, the pattern immediately throws a runtime exception.

Syntax

<subpattern>!
The pattern consists of a subpattern followed by the postfix ! operator. It binds the non-null value to the subpattern.

Evaluation Semantics

When the Dart runtime evaluates a null-assert pattern against a value v:
  1. It checks if v is null.
  2. If v is null, execution halts, and a TypeError is thrown.
  3. If v is not null, v is cast to its non-null base type and passed to the inner <subpattern> for further matching or binding.

Type Promotion and Binding

The primary mechanical function of the null-assert pattern is to force type promotion during destructuring or pattern matching.
// Variable declaration pattern
int? nullableValue = 10;
var (promotedValue!) = nullableValue; 
// promotedValue is strictly typed as 'int'
In control flow structures, the null-assert pattern alters standard exhaustiveness and fall-through behaviors. Because a null value triggers an exception rather than a match failure, it does not pass control to subsequent cases.
// Switch statement pattern
void processValue(String? input) {
  switch (input) {
    case String s!: 
      // 's' is promoted to non-nullable String.
      // If 'input' is null, this throws rather than skipping to another case.
      print(s);
  }
}

Destructuring with Null-Assert

The pattern can be nested within record, list, object, or map patterns to assert the non-nullability of specific elements during extraction.
// Record destructuring
(int?, int?) coordinates = (5, 10);
var (x!, y!) = coordinates; 
// Both x and y are extracted and promoted to non-nullable 'int'.
// Throws if either element in the tuple is null.

Contrast with Null-Check Pattern

Mechanically, the null-assert pattern (!) differs strictly from the null-check pattern (?). While ? safely fails the match on a null value and allows the switch or if-case to evaluate the next branch, ! acts as a hard assertion, terminating the control flow with an exception if a null value is encountered.
Master Dart with Deep Grasping Methodology!Learn More