Search code examples
flutterflutter-layoutflutter-webflutter-animation

How to color a text in Flutter


I was trying to add color to my Overweight and Underweight with the color red. Could you help me by letting me know how can I do that?

Here is the code:

import 'dart:math';

class CalculatorBrain {
   CalculatorBrain({this.height, this.weight});

  final int height;
  final int weight;

  double _bmi;

  String calculateBMI() {
    _bmi = weight / pow(height / 100, 2);
    return _bmi.toStringAsFixed(1);
  }

  String getResults(){
    if (_bmi >= 25) {
      return 'Overweight';
    } else if (_bmi > 18.5) {
      return 'Normal';
    } else {
      return 'Underweight';
    }
  }

  String getInterpretation () {
    if (_bmi >= 25) {
      return 'You have a higher than normal weight. Try to exercise more.';
    } else if (_bmi > 18.5) {
      return 'You have a normal body weight. Good job!';
    } else {
      return 'You have a lower than normal body weight. You can eat a bit more.';
    }
  }

}

Solution

  • you can refer to below shared code and change it as per your requirement

    Widget getTextWidget(String text){
       Color textColor;
       if(text.toLowerCase().contains("overweight") || text.toLowerCase().contains("underweight"))
           textColor=Colors.red;
       else textColor=Colors.black;
    
       return Text(text, 
              style:TextStyle(color: textColor));
    }
    

    call the getTextWidget("your text here") widget function in your widget tree where you want to show the text