Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a Ternary Operator with multiple condition in flutter dart?

Tags:

how to use ternary if else with two or more condition using "OR" and "AND" like

    if(foo == 1 || foo == 2)      {       do something       }      {       else do something       }  

i want to use it like

  foo == 1 || foo == 2 ? doSomething : doSomething 
like image 406
Kamal Gayan Avatar asked Feb 07 '19 06:02

Kamal Gayan


People also ask

How do you handle 3 conditions in a ternary operator?

The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark ( ? ), then an expression to execute if the condition is truthy followed by a colon ( : ), and finally the expression to execute if the condition is falsy.

How do you use the ternary operator in Dart?

The ternary operator is a shorthand version of an if-else condition. There are two types of ternary operator syntax in Dart, one with a null safety check and the other is the same old one we encounter normally.

Can we have multiple statements in ternary operator?

Yes, we can, but with one proviso… There is no block demarcation so that action should be simple, else it would be better to abstract it away in a function and call the function from the ternary.


1 Answers

If you're referring to else if statements in dart, then this ternary operator:

(foo==1)? something1():(foo==2)? something2(): something3(); 

is equivalent to this:

if(foo == 1){     something1(); } elseif(foo == 2){     something2(); } else something3(); 
like image 58
James Casia Avatar answered Sep 17 '22 14:09

James Casia