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

两盒软妹~` 提交于 2020-07-17 05:45:08

问题


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

回答1:


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

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

is equivalent to this:

if(foo ==1){
    something1();
}
elseif(foo ==2){
    something2();
}
elseif(foo ==3){
    something3();
}
else something4();



回答2:


Try below

(2 > 3)?print("It is more than 3"):print("It is less than 3");
////Prints It is less than 3 to the console



回答3:


For three conditions use:

value: (i == 1) ? 1 : (i == 2) ? 2 : 0




回答4:


it is easy,

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

it can be written thus for OR statement

foo==1 || foo==2 ? do something : else do something

it can be written thus for AND statement

foo==1 && foo==2 ? do something : else do something

both will work perfectly




回答5:


The cleaner way for me is

if ({1, 2}.contains(foo)) {
  //do something
} else {
  //do something else
}



回答6:


void main(){
  var a,b,c,d;  
  a = 7;  
  b = 9;  
  c = 11;  
  d = 15;  
  print((a>b)?((a>c)?((a>d)?a:d):c):(b>c)?((b>d)?b:d):(c>d)?c:d);
}


来源:https://stackoverflow.com/questions/54567254/how-to-use-a-ternary-operator-with-multiple-condition-in-flutter-dart

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!