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 ??= operator is a null-aware compound assignment operator in Dart. It evaluates the left-hand operand and assigns the value of the right-hand expression to it strictly if the left-hand operand evaluates to null. As an expression, the operation yields the final value of the left-hand operand, allowing it to be used inline within larger expressions.
leftOperand ??= rightExpression;
Evaluation Mechanics
- Expression Yield: Because
??= is an expression rather than a statement, it evaluates to a value. This distinguishes it from an if (x == null) { x = y; } block, which is a statement that yields no value.
int? x;
print(x ??= 5); // Assigns 5 to x, evaluates to 5, and prints 5
2. **Single Receiver Evaluation:** When the left-hand operand involves a property access, the compound `??=` operator guarantees the receiver is evaluated exactly once. The expression `obj.value ??= y` is semantically distinct from the expanded form `obj.value = obj.value ?? y`, as the expanded form evaluates the receiver (`obj`) twice.
3. **Short-Circuiting:** The operator utilizes short-circuit evaluation. If the left-hand operand evaluates to a non-null value, the right-hand expression is completely ignored and never executed.
4. **Type Constraints:** The right-hand expression must yield a value whose type is assignable to the left-hand operand. While typically applied to nullable types, Dart permits the use of `??=` on non-nullable types. Doing so is not a compile-time error, though it triggers a static analyzer warning for dead code since the left side can never be `null` and the right side is unreachable.
## Behavioral Examples
**Null Operand Assignment:**
```dart
int? a;
a ??= 10; // 'a' is null, 10 is assigned. Expression evaluates to 10.
Non-Null Operand Bypass:
int? b = 5;
b ??= 20; // 'b' is not null, assignment is bypassed. Expression evaluates to 5.
Short-Circuit Execution:
int? c = 100;
int computeValue() {
print("Evaluated");
return 50;
}
c ??= computeValue(); // computeValue() is never called; 'c' remains 100.
Master Dart with Deep Grasping Methodology!Learn More