How to use If statement in Flutter widget
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,
),
),
),
),
Solution 1:
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),
Solution 2:
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)),
])