How to change text color based on checkbox value - Flutter

469

Instead of setting a variable for storing the right color, try assesing the right color in getTextColor() and return that to the style property of your text. This way the text color will always be recomputed everytime you setState((){})

Below is an implementation of the same. See if it helps.

class _MyHomePageState extends State<MyHomePage> {
  bool isChecked = false;
  @override
  Widget build(BuildContext context) {
    String text = "AABB";

    Color getTextColor(String textToBeAssesed) {
      if (isChecked) {
        //Logic to be checked if checkbox is clicked
        if (text == 'AABB' || text == 'AaBb') {
          return Colors.blueAccent;
        } else {
          return Colors.black;
        }
      } else {
        //Logic to be checked if checkbox is unticked
        return Colors.black;
      }
    }

    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Checkbox(
              value: isChecked,
              onChanged: (value) {
                setState(() {
                  isChecked = !isChecked;
                });
              },
            ),
            Text(
              text,
              style: TextStyle(color: getTextColor(text)),
            ),
          ],
        ),
      ),
    );
  }
}
Share:
469
bilbo_bo
Author by

bilbo_bo

Updated on January 01, 2023

Comments

  • bilbo_bo
    bilbo_bo over 1 year

    I want to change the text color if the checkbox is selected but I am stuck. I have a function called getTextColor that should define which color should be used depending on the text.

    In that case, when the checkbox is selected, it should check if the text has an 'A' in it and, if so, apply the blue color. How to achieve this?

    Here is how I am trying to build it:

    class _MainScreenState extends State<MainScreen> {
      bool? dominant_A = false;
    
      Color getTextColor(String text) {
        var TheRightColor = Colors.black;
    
        if (text == 'AABB' || text == 'AaBb') {
          TheRightColor = Colors.blueAccent;
        } 
    
        return TheRightColor;
      }
    
      // Here is the structure of the checkbox
      void _onDominant_A(bool? newValue) => setState(() {
            dominant_A = newValue;
    
            if (dominant_A ?? true) {
              // Here should be the logic that applies the blue color to 'AABB' and 'AaBb' (both has an 'A').
    
            } 
          });
    

    Here is how it's called later:

             TextSpan(
                      text: widget.result + '  ',
                      style: TextStyle(
                        fontSize: 20.0,
                        fontWeight: FontWeight.bold,
                        color: object.getTextColor(widget.result), // The result is the text
                        height: 2.5,
                        letterSpacing: 0.7,
                      )),
    

    Additional information: I'm not sure if the function getTextColor needs to exist. I just put it there because I don't know how to call it later like I did in the second code.

  • bilbo_bo
    bilbo_bo over 2 years
    The only problem is with the Text() at the end of your code. In my case, this Text() is in another class that displays the widget.result (the text itself). How could I access it?
  • bilbo_bo
    bilbo_bo over 2 years
    Thank you! I am testing it, but it seems that the getColor() is requiring a return statement at the end of it. What should I put there?
  • Jessé Lopes Pereira
    Jessé Lopes Pereira over 2 years
    I updated, try again
  • bilbo_bo
    bilbo_bo over 2 years
    In checkText(widget.result) it appears this error: The getter 'result' isn't defined for the type 'MainScreen'.
  • bilbo_bo
    bilbo_bo over 2 years
    Só agora percebi que você também é brasileiro!
  • Jessé Lopes Pereira
    Jessé Lopes Pereira over 2 years
    Haha, fica mais fácil! você definiu result na sua classe? Exemplo: const MainScreen({Key? key, required this.result}) : super(key: key); final String result;
  • bilbo_bo
    bilbo_bo over 2 years
    Eu fiz isso em outra classe, porque tenho que fazer esse result aparecer na próxima tela aí criei uma classe pra próxima tela e defini esse result
  • Jessé Lopes Pereira
    Jessé Lopes Pereira over 2 years
    O erro que você descreveu acima significa que o result não está definido para MainScreen. De onde você está recebendo o result?
  • bilbo_bo
    bilbo_bo over 2 years
    O TextSpan na verdade está dentro de outra classe (a mesma classe da próxima página que mencionei acima). Aí eu estava conseguindo acessar o result por causa disso. Ele estava definido lá. Eu teria que defini-lo novamente na MainScreen?
  • Jessé Lopes Pereira
    Jessé Lopes Pereira over 2 years
    Eu não vejo outra saída a não ser definir o return na mesma classe que o TextSpan, por que se não for definido, a função não funciona. Desculpe, sou leigo.
  • bilbo_bo
    bilbo_bo over 2 years
  • bilbo_bo
    bilbo_bo over 2 years
    Vou estar com o chat aberto, aí quando for voltar é só dar um toque por lá :D
  • RIP71DE
    RIP71DE over 2 years
    If your Text() lies in a child class, the you can always pass getTextColor() to the child class as an argument since dart treats all functions as first class data objects.
  • bilbo_bo
    bilbo_bo over 2 years
    Oie Jessé @JesseLopesPereira! Posso te chamar num bate-papo privado? Queria tirar uma dúvida sobre uma parte de meu projeto. :D