skip to Main Content

I have a Flutter program in which the click of a button changes something depending on the state of the button. I implemented it using ternary operator (which calls functions) and also with just an if-else block.

Using ternary:

 void functionA() {

 setState(() {
   //assignment op
   //assignment op
   //method call of a Dart class {
   //another setState }
   });
  }

 void functionB() {

  //method call of a Dart class
 }

 //in widget:

  ElevatedButton(
          onPressed: () {
            a = !a;
            a ? functionA(): functionB();
          }
        )`

Using if-else:

ElevatedButton(
          onPressed: () {
           a = !a;
           if (a){

            //same sequence of operations as functionA()
           
            }else{
             
            //same sequence of operations as functionB()
            }
 
        )`

The code using the if-else statement is fewer lines versus the ternary operator that calls functions so which would be more optimal?

2

Answers


  1. They both work; it is just that the if-else is more readable than the ternary.

    Login or Signup to reply.
  2. IF ELSE condition is more readable and clear.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search