Skip to main content
The null-aware assignment operator (??=) assigns the value of the right-hand operand to the left-hand operand if and only if the left-hand operand is currently null. If the left-hand operand is non-null, the assignment is skipped, and the right-hand expression is not evaluated.

Syntax

variable ??= expression;

Operational Logic

The operation a ??= b is semantically equivalent to the following control flow:
if (a == null) {
  a = b;
}

Behavior and Evaluation

The operator exhibits short-circuit behavior. The Dart runtime evaluates the variable on the left side first.
  1. If the variable is null: The expression on the right is evaluated, and its result is assigned to the variable.
  2. If the variable is non-null: The expression on the right is not evaluated. Any side effects (such as function calls) contained within the right-hand expression will not occur.

Examples

Assignment to a Null Variable
int? value = null;

// value is null, so 10 is assigned
value ??= 10; 

print(value); // Output: 10
Assignment to a Non-Null Variable
int? value = 5;

// value is non-null, so the assignment is ignored
value ??= 10; 

print(value); // Output: 5
Short-Circuit Evaluation
int? value = 5;

int computeValue() {
  print('Computing...');
  return 10;
}

// value is non-null; computeValue() is never executed
value ??= computeValue(); 

// Output: 5
// Note: 'Computing...' is never printed to the console.
Master Dart with Deep Grasping Methodology!Learn More