简体   繁体   中英

Conditional color change Dart Flutter

I want to change the color of the variable according to its value. How do I implement text style to a variable, here is the code:

@override
  initState() {
    _volume = 0;
    grade = '-';
  }

  void _calculation() {
    setState(
      () {
        _volume = ((double.parse(lenCon.text)) /
            (double.parse(widCon.text) * double.parse(widCon.text)));
      },
    );      
if (_volume >= 35) {
          grade = 'High';
        } else if (_volume <= 34.9 && _volume >= 30)
          grade = 'Low';

I want to get the "High" in red and "Low" in blue how can I do it? Why can't I use style: in the if statement for example;

grade = 'High', style: new TextStyle(fontSize: 18.0, color: Colors.white)

You can create a color variable and initialize it with a default color. Then if you call _calculation() you can call setState after setting the grade and set the color depending on grade

Color colors;
setState(() {
   if(grade == 'High'){
     color = Colors.red;
   } else if(grade == 'Low'){
     color = Colors.blue;   
   } else {
     color = Colors.white;
   }
});

And your Text Widget should look like that.

Text('MyText', style: TextStyle(color: color)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM