What means the operator "??" in Dart/Flutter?

5,739

Solution 1

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.

Solution 2

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.
Share:
5,739
cyberpVnk
Author by

cyberpVnk

Updated on December 25, 2022

Comments

  • cyberpVnk
    cyberpVnk over 1 year

    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); ```