Skip to main content
The null-aware spread operator (...?) allows for the expansion of a nullable collection expression into a target collection literal. It functions identically to the standard spread operator (...) when the operand is non-null, but safely omits the operation if the operand evaluates to null, preventing a runtime exception.

Syntax

The operator is used as a prefix within collection literals (Lists, Sets, and Maps).
[elem, ...?nullableIterable, elem]
{elem, ...?nullableSet, elem}
{key: value, ...?nullableMap}

Operational Logic

When the Dart runtime encounters ...?expression:
  1. Evaluation: The expression to the right of the operator is evaluated.
  2. Null Check:
    • If the result is null: The operator does nothing. No elements are added to the target collection, and execution continues to the next element in the literal.
    • If the result is non-null: The operator behaves exactly like the standard spread operator (...), iterating over the collection and inserting its individual elements (or key-value pairs) into the target.

Code Demonstration

The following example demonstrates the operator’s behavior with both null and non-null references in List and Map contexts.
void main() {
  // 1. List Context
  List<int>? nullList;
  List<int>? populatedList = [2, 3];

  // If nullList is null, it is skipped.
  // If populatedList is valid, its elements are expanded.
  var combinedList = [
    1, 
    ...?nullList, 
    ...?populatedList, 
    4
  ];
  
  print(combinedList); // Output: [1, 2, 3, 4]

  // 2. Map Context
  Map<String, String>? nullMap;
  Map<String, String>? populatedMap = {'b': 'Bravo'};

  var combinedMap = {
    'a': 'Alpha',
    ...?nullMap,
    ...?populatedMap
  };

  print(combinedMap); // Output: {a: Alpha, b: Bravo}
}

Type Constraints

  • Iterables: When used in a List or Set literal, the expression must evaluate to a type assignable to Iterable<T>?, where T is compatible with the target collection’s element type.
  • Maps: When used in a Map literal, the expression must evaluate to a type assignable to Map<K, V>?, where K and V are compatible with the target map’s key and value types.
Master Dart with Deep Grasping Methodology!Learn More