What means the operator "??" in Dart/Flutter? [duplicate]
Asked Answered
P

3

10

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); ```
Poff answered 3/11, 2020 at 13:59 Comment(5)
Whyever did you toss the java tag in there? Removed it for you :)Destroy
?? operator check this outPrecipitin
(#54032304)Precipitin
Does this answer your question? Whats ??= operator in DartJackelynjackeroo
This is explained in the Dart Language Tour.Aymer
D
14

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.

Destroy answered 3/11, 2020 at 14:2 Comment(0)
L
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.
Lettuce answered 3/11, 2020 at 14:6 Comment(0)
M
0

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

Monamonachal answered 3/11, 2020 at 14:52 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.