8

I'm new in flutter and practicing simple app. But now, I can insert one line conditional statement but I want to add If statement. So I can add more statement. How do I do that? Here is my code. Please have a look. I want to add more color when I reach targeted amount color: _moneyCounter > 1000 ? Colors.green : Colors.red,

Expanded(
              child: Center(
                child: Text(
                  '\USD $_moneyCounter',
                  style: TextStyle(
                    color: _moneyCounter > 1000 ? Colors.green : Colors.red,
                    fontSize: 40.0,
                  ),
                ),
              ),
            ),

3 Answers 3

23

You can so multiple ternary operators :

_moneyCounter > 1000 ? Colors.green : _moneyCounter > 2000 ? Colors.Blue : Colors.red

But for readability i don't recommend doing this so you can use a function that will return the color :

Color getMyColor(int moneyCounter) {
 if (moneyCounter == 1000) then {
    return Colors.green;
 } else
  if (moneyCounter == 2000) then {
   return Colors.red;
  }
}

and then use that function :

color: getMyColor(_moneyCounter),
Sign up to request clarification or add additional context in comments.

2 Comments

Hello Sir @Raouf Rahiche, Thank you so much but could you please complete the Return Method. So I can follow
check the answer again
9

You can use different widgets as below,

Column(
    children: [
        if (_id == 0) ...[
          Container()
        ] else if(_id == 1)...[
          Text("Hello")
        ] else ...[
          SizedBox(height: 20)
        ],
    ],
 ),

1 Comment

Didn't see that in the documentation. Saved me a ton of time. Thanks
1

if you use in Column

Column(children:[  if (e["index"] == 1)
              Text(e["text"].toString(),
                  textAlign: TextAlign.center,
                  style: TextStyle(color: Colors.green[900])),
            if (e["index"] == 2)
              Text(e["text"].toString(),
                  textAlign: TextAlign.center,
                  style: TextStyle(color: Colors.green)),
            if (e["index"] == 3)
              Text(e["text"].toString(),
                  textAlign: TextAlign.center,
                  style: TextStyle(color: Colors.amber)),
            if (e["index"] == 4)
              Text(e["text"].toString(),
                  textAlign: TextAlign.center,
                  style: TextStyle(color: Colors.orange)),
            if (e["index"] == 5)
              Text(e["text"].toString(),
                  textAlign: TextAlign.center,
                  style: TextStyle(color: Colors.red)),
          ])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.