Home > Mobile >  How to write multiple conditions in dart?
How to write multiple conditions in dart?

Time:10-28

I understand we are able to write a condition in property as ternary operator as follows

onTap: textType == "birth"
                ? () {
                    FocusScope.of(context).requestFocus(FocusNode());
                    showPicker(context, birthController,ref);
                  }
                : null,

but when it comes to multiple conditions, how can I rewrite the code like? as the code shown below treated as syntax error.

onTap:
if (textType == "birth"){
 //do something
}else if(textType == "place"){
//do something
}else{
 return null
}

CodePudding user response:

You have to use nested ternary operators. It's sort of ugly, but it's how you do it.

Example: myVar ? "hello" : myVar2 ? "hey" : "yo"

This checks the first condition (myVar) then if that fails, checks the second condition (myVar2). You can also do actual checks here in place of just checking a boolean value. For example: myVar == 14

Alternatively, you can just call a function from your code, where you use if/else if/else etc. This is what I would recommend.

For example, call getProperGreeting() from your code, which would refer to:

String getProperGreeting() {
... <if else chain> ...

}

CodePudding user response:

Try this:

onTap: textType == "birth" ? () {
     //do something when textType == "birth"
   } : textType == "place" ? () {
     //do something when textType == "place"
   } : () {
     //do something else
   }
  • Related