The Dart null-aware operators

The Dart null-aware operators #

null operator ?? #

Called also null operator . This operator returns expression on its left , except if it is null , and if so, it returns right expression:

void main() {
  print(0 ?? 1);  // <- 0
  print(1 ?? null);  // <- 1
  print(null ?? null); // <- null
  print(null ?? null ?? 2); // <- 2
}

null-aware assignment ??= #

Called also null-aware assignment . This operator assigns value to the variable on its left, only if that variable is currently null :

void main() {
  int value;
  print(value); // <- null
  value ??= 5;
  print(value); // <- 5, changed from null
  value ??= 6;
  print(value); // <- 5, no change
}

null-aware access ?. #

Called also null-aware access (method invocation). This operator prevents you from crashing your app by trying to access a property or a method of an object that might be null :

void main() {
  String value; // <- value is null
  print(value.toLowerCase()); // <- will crash
  print(value?.toLowerCase().toUpperCase());  // <- will crash
  print(value?.toLowerCase()?.toUpperCase()); // <- output is null
}

null-aware spread operator …? #

Called also null-aware spread operator . This operator prevents you from adding null elements using spread operator(lets you add multiple elements into your collection):

void main() {
  List<int> list = [1, 2, 3];
  List<String> list2; // <- list2 is null
  print(['chocolate', ...?list2]); // <- [chocolate]
  print([0, ...?list2, ...list]); // <- [0, 1, 2, 3]
  print(['cake!', ...list2]);  // <- will crash
}

Ternary operator ? #

And for bonus, ? operator. Looking similar to those we already saw, this is NOT a null-aware operator, but a ternary one. Ternary operator is used across many languages, so you should be familiar with it. This is how it looks:

expression ? option1 : option2

If expression is true it goes with the option1 and if not, with the option2.

void main() {
  print(2 == 2 ? "a truth" : "a lie"); // <- a truth
  print(1 == 2 ? "a truth" : "a lie"); // <- a lie  5 == 6 ? doThis() : doThat(); // <- done that
}void doThis() {
  print('done this');
}void doThat() {
  print('done that');
}