Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any ternary operator for just single if condition in dart?

In dart we have plenty of ternary operators. But do we have one ternary operator just for if condition?

Example

In condition

if (num == 1){
  print(true);
} else {
  print(false);
}

In ternary

print(num == 1 ? true : false);

So do we have any ternary operator just for true condition like above example?

if (num == 1) {
   print(true);
}
like image 607
Devarsh Ranpara Avatar asked Oct 31 '25 07:10

Devarsh Ranpara


1 Answers

No.

The conditional operator ?/: in Dart requires all three operands. It does so because all expressions must have a value, and if you could do just e1 ? e2, then the expression has no value if e1 is false.

It's not impossible to conceive of a binary conditional operator where the missing expression defaults to null, say (e1?:elseExpression) or (e1?thenExpression:), but then you can also just write the null, and saving four letters is probably not worth the potential loss of readability.

Ob-nitpick. The conditional operator in Dart is one of two ternary operators (operators requiring three operands, like binary operators require two operands), the other ternary operator being []=.

like image 105
lrn Avatar answered Nov 01 '25 21:11

lrn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!