8

I've seen this code and need an explanation for "??". I know ternary operators like "?" and then the true-condition and after ":" the false/else condition. But what means the double "??" ?

Thanks in advance

      widget.secondaryImageTop ??
      (widget.height / 2) - (widget.secondaryImageHeight / 2); ```
rzwitserloot
  • 85,357
  • 5
  • 51
  • 72
cyberpVnk
  • 109
  • 1
  • 1
  • 2
  • Whyever did you toss the java tag in there? Removed it for you :) – rzwitserloot Nov 03 '20 at 14:01
  • [?? operator](http://blog.sethladd.com/2015/07/null-aware-operators-in-dart.html) check this out – Arpit Awasthi Nov 03 '20 at 14:03
  • (https://stackoverflow.com/questions/54031804/what-are-the-double-question-marks-in-dart#:~:text=answer%20was%20accepted%E2%80%A6-,The%20%3F%3F,operator%20means%20%22if%20null%22.&text=Another%20related%20operator%20is%20%3F%3F%3D,.) – Arpit Awasthi Nov 03 '20 at 14:03
  • Does this answer your question? [Whats ??= operator in Dart](https://stackoverflow.com/questions/64642572/whats-operator-in-dart) – bluenile Nov 03 '20 at 14:15
  • This is explained in [the Dart Language Tour](https://dart.dev/guides/language/language-tour#conditional-expressions). – jamesdlin Nov 03 '20 at 18:14

3 Answers3

12

List of all dart operators

it's the coalesce operator.

a ?? b

means: if a is not null, it resolves to a. if a is null, it resolves to b.

SQL and a few other languages have this operator.

rzwitserloot
  • 85,357
  • 5
  • 51
  • 72
5

You example:

widget.secondaryImageTop ??
      (widget.height / 2) - (widget.secondaryImageHeight / 2);

This will use widget.secondaryImageTop unless it is null, in which case it will use (widget.height / 2) - (widget.secondaryImageHeight / 2).

Source and detail, including dartpad where you can try things out with pre-populated examples: https://dart.dev/codelabs/dart-cheatsheet

An example from that documentation, using the = sign as well.

the ??= assignment operator, which assigns a value to a variable only if that variable is currently null:

int a; // The initial value of a is null.
a ??= 3;
print(a); // <-- Prints 3.

a ??= 5;
print(a); // <-- Still prints 3.
Scott
  • 236
  • 2
  • 7
0

It means => if exists and if not null...

Luiggi
  • 358
  • 4
  • 12