Skip to main content
The null-aware cascade operator (?..) is a syntactic sugar that allows a sequence of operations to be performed on a target object only if that object is not null. It combines the functionality of the standard cascade operator (..) with short-circuiting null safety checks.

Syntax

receiver?..member = value
        ..method();

Operational Semantics

The ?.. operator functions according to the following execution flow:
  1. Receiver Evaluation: The expression to the left of the operator (the receiver) is evaluated once.
  2. Null Check:
    • If the receiver evaluates to null, the entire cascade expression short-circuits and immediately returns null. No subsequent methods or property setters in the chain are executed.
    • If the receiver evaluates to a non-null object, the operations defined in the cascade are executed sequentially.
  3. Return Value: Unlike the dot operator (.) or the null-aware dot operator (?.), which return the result of the member access, the null-aware cascade operator returns the receiver (the original object) or null.

Code Visualization

The following example demonstrates the mechanical difference between a standard cascade and a null-aware cascade when handling nullable types.
class Configuration {
  String? mode;
  int? timeout;
  
  void log() => print('Configured');
}

void main() {
  // Scenario 1: The receiver is instantiated (not null)
  Configuration? validConfig = Configuration();
  
  // The operations execute, and 'validConfig' is returned.
  Configuration? result1 = validConfig
    ?..mode = 'DEBUG'
    ..timeout = 5000
    ..log(); 

  print(result1?.mode); // Output: DEBUG

  // Scenario 2: The receiver is null
  Configuration? nullConfig = null;

  // The expression short-circuits. 
  // 'mode' is not set, 'log' is not called.
  // The expression evaluates to null.
  Configuration? result2 = nullConfig
    ?..mode = 'PROD' 
    ..log();

  print(result2); // Output: null
}

Chaining Behavior

When starting a cascade chain with ?.., subsequent operations in the same chain typically use the standard cascade operator (..). The initial null check provided by ?.. guards the entire chain; if the receiver is null, the subsequent .. operations are skipped entirely.
// If 'maybeObject' is null, neither methodA nor methodB executes.
maybeObject
  ?..methodA()
  ..methodB();
Master Dart with Deep Grasping Methodology!Learn More