How to change text color based on checkbox value - Flutter
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)),
),
],
),
),
);
}
}
bilbo_bo
Updated on January 01, 2023Comments
-
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 over 2 yearsThe only problem is with the
Text()
at the end of your code. In my case, thisText()
is in another class that displays thewidget.result
(the text itself). How could I access it? -
bilbo_bo over 2 yearsThank 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 over 2 yearsI updated, try again
-
bilbo_bo over 2 yearsIn
checkText(widget.result)
it appears this error:The getter 'result' isn't defined for the type 'MainScreen'
. -
bilbo_bo over 2 yearsSó agora percebi que você também é brasileiro!
-
Jessé Lopes Pereira over 2 yearsHaha, 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 over 2 yearsEu 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 esseresult
-
Jessé Lopes Pereira over 2 yearsO erro que você descreveu acima significa que o
result
não está definido para MainScreen. De onde você está recebendo oresult
? -
bilbo_bo over 2 yearsO
TextSpan
na verdade está dentro de outra classe (a mesma classe da próxima página que mencionei acima). Aí eu estava conseguindo acessar oresult
por causa disso. Ele estava definido lá. Eu teria que defini-lo novamente na MainScreen? -
Jessé Lopes Pereira over 2 yearsEu não vejo outra saída a não ser definir o
return
na mesma classe que oTextSpan
, por que se não for definido, a função não funciona. Desculpe, sou leigo. -
bilbo_bo over 2 yearsLet us continue this discussion in chat.
-
bilbo_bo over 2 yearsVou estar com o chat aberto, aí quando for voltar é só dar um toque por lá :D
-
RIP71DE over 2 yearsIf your
Text()
lies in a child class, the you can always passgetTextColor()
to the child class as an argument since dart treats all functions as first class data objects. -
bilbo_bo over 2 yearsOie Jessé @JesseLopesPereira! Posso te chamar num bate-papo privado? Queria tirar uma dúvida sobre uma parte de meu projeto. :D