SugiuraY
SugiuraY

Reputation: 361

How to write multiple conditions in dart?

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
}

Upvotes: 3

Views: 914

Answers (3)

Soliev
Soliev

Reputation: 1376

You wanna use custom method to handle onTap with condition

onTap: _onTapHandler

  void _onTapHandler() {
    if(textType=='birth'){
      //do something
      }else if(textType=='place'){
        //do something else
      }
      else if(textType == 'foo'){
        //bar
      }
  }

or use nested ternary operators as mentioned above.

Upvotes: 2

manhtuan21
manhtuan21

Reputation: 3475

Try this:

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

Upvotes: 2

Matthew Trent
Matthew Trent

Reputation: 3274

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> ...

}

Upvotes: 4

Related Questions