'How to use a Ternary Operator with multiple condition in flutter dart?
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
Solution 1:[1]
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();
Solution 2:[2]
For three conditions use:
value: (i == 1) ? 1 : (i == 2) ? 2 : 0
Solution 3:[3]
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
Solution 4:[4]
For AND try this, // here both or multiple conditions needs to satisfy
if (primaryImageUploaded == true && signatureImageUploaded == true) {
// status bool condition in true
} else {
// if false
}
For OR try this, // here need ONLY any one condition to satisfy
if (primaryImageUploaded == true || signatureImageUploaded == true) {
// status bool condition in true
} else {
// if false
}
Another Dart Syntax
if (100 > 50) {
print("100 is greater than 50");
}
Solution 5:[5]
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
Solution 6:[6]
Here is an example of the same
Text((managerStatus == "pending")
? "Requested"
: (adminStatus == "confirm")
? "Amount credited"
: "Admin Pending")
Solution 7:[7]
EDITED
The original answer has run a little bit of from the question asked. Below is my edited answer.
To use ternary operator
(foo == 1 || foo == 2) ? doSomething() : doSomethingElse();
For my cleaner approach
{1, 2}.contains(foo) ? doSomething() : doSomethingElse();
ORIGINAL
The cleaner way for me is
if ({1, 2}.contains(foo)) {
//do something
} else {
//do something else
}
Solution 8:[8]
Simple Multiple check in one condition
if(in_array($foo, [1,2,'other'])) {
//do something
}
else {
//else do something
}
Solution 9:[9]
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);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | el2e10 |
| Solution 3 | Mehul Kabaria |
| Solution 4 | AzeTech |
| Solution 5 | Muhammad Dyas Yaskur |
| Solution 6 | jerald jacob |
| Solution 7 | |
| Solution 8 | step |
| Solution 9 | SHR |
