Search code examples
flutterif-statementconditional-statementsconditional-operator

flutter ternary operator with multiple statements to run


I dont want to put more conditions in ternary operator, rather run 2 statements after evaluating a single condition.

if-else structure would be:

    if( maleCardColor == inactiveCardColor ) {
// i want to run both these lines in ternary operator
      **maleCardColor = activeCardColor;
      femaleCardColor = inactiveCardColor;**

        } else {
          maleCardColor = inactiveCardColor;
    }

i want to use it like:_

  maleCardColor = (maleCardColor==inactiveCardColor)?   (maleCardColor = activeCardColor   &&   femaleCardColor = inactiveCardColor) : maleCardColor = inactiveCardColor ,

Solution

  • As per my knowledge, if you want to use multi-line in the ternary operator, you can make two methods as mentioned below.

      ("A" == "B") ? ternaryTrueMethod() : ternaryFalseMethod();
    
      void ternaryTrueMethod() {
        /*
        multi-line code here
         */
        return;
      }
    
      void ternaryFalseMethod() {
        /*
        multi-line code here
         */
        return;
      }
    

    The first method is for ternary satisfied & the other one is for ternary unsatisfied.