Skip to main content
The null-coalescing operator (??) is a binary operator that evaluates to the value of its left-hand operand if it is not null; otherwise, it evaluates and returns the right-hand operand.

Syntax

expression1 ?? expression2

Evaluation Logic

The operator follows a strict evaluation order with short-circuiting behavior:
  1. Evaluate Left Operand: expression1 is evaluated.
  2. Null Check:
    • If expression1 is non-null, the operation resolves immediately to the value of expression1. expression2 is not evaluated.
    • If expression1 is null, expression2 is evaluated, and its result becomes the result of the operation.

Short-Circuiting

Because the operator short-circuits, any side effects (such as function calls, I/O, or variable mutations) contained within the right-hand operand will only occur if the left-hand operand is null.

Examples

Basic Evaluation
String? nullableName = null;
String nonNullableName = 'Dart';

// Result is 'Default' because nullableName is null
print(nullableName ?? 'Default'); 

// Result is 'Dart' because nonNullableName is not null
print(nonNullableName ?? 'Default'); 
Lazy Evaluation
String? activeValue = 'Existing';

String computeExpensiveValue() {
  print('Computing...');
  return 'Computed';
}

// "Computing..." is NOT printed.
// The function is never called because activeValue is not null.
var result = activeValue ?? computeExpensiveValue();

Static Type Analysis

  • Left Operand: Should be of a nullable type. If the static type of the left operand is non-nullable, the operator is redundant, and the Dart analyzer will issue a warning.
  • Return Type: The static type of the expression a ?? b is the least upper bound (LUB) of the type of a (promoted to non-nullable) and the type of b.
Master Dart with Deep Grasping Methodology!Learn More