What are the ?? double question marks in Dart?

2019-04-19 18:51发布

问题:

The following line of code has two question marks:

final myStringList = prefs.getStringList('my_string_list_key') ?? [];

What is the meaning?

回答1:

The ?? double question mark operator means "if null". Take the following expression, for example.

String a = b ?? 'hello';

This means a equals b, but if b is null then a equals 'hello'.

Another related operator is ??=. For example:

b ??= 'hello';

This means if b is null then set it equal to hello. Otherwise, don't change it.

Reference

  • A Tour of the Dart Language: Operators
  • Null-aware operators in Dart

Note

  • In Swift ?? is called a nil-coalescing operator, where nil means null. I couldn't find an official name for the ?? operator in the Dart documentation, but calling it a null-aware operator seems pretty good.