What are ??, ??=, ?., ...? in Dart?

·

2 min read

These are null-aware operators in Dart and they shorten your code a lot.

??

Also called the null operator. This operator returns the expression on its left, except if it is null, and if so, it returns the right expression:

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

??=

Also called the 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
}

?.

Also called 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
}

...?

Also called the null-aware spread operator. This operator prevents you from adding null elements using the spread operator(lets you add multiple elements to 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
}

?

And with all these question marks, do not forget the ternary operator (? operator). The 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 ? 
}

Use dartpad.dartlang.org for testing examples.