I am trying to change my labelText color when focused. I can change the text color but not when focused.
I have tried all the hint text colors and label text colors, but nothing helps.
Container(
padding: EdgeInsets.fromLTRB(15, 10, 15, 0),
child: TextFormField(
cursorColor: Colors.lightGreen,
keyboardType: TextInputType.phone,
decoration: InputDecoration(
labelText: 'Phone Number',
hintText: 'Enter a Phone Number',
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(
color: Colors.lightGreen
)
),
border: OutlineInputBorder(
borderSide: BorderSide()
),
)
),
),
Here are images of what is happening:


TextField and TextFormField both have an argument called enabled. You can control it using a boolean variable. enabled=true means it will act as an editing text field whereas enabled=false will Disable the TextField Widget.
You'd need to have a way determine its focus state and then create a conditional for its color based off of that. This is where a focusNode would be helpful. Construct a new FocusNode off the widget creation, use that as the focusNode property in the TextFormField. Then in color property of the TextStyle property of the TextFormField you could add something like:
FocusNode myFocusNode = new FocusNode();
...
return TextFormField(
focusNode: myFocusNode,
decoration: InputDecoration(
labelText: 'test',
labelStyle: TextStyle(
color: myFocusNode.hasFocus ? Colors.blue : Colors.black
)
),
);
EDIT : Just a quick note, you'll probably need to make sure this is in a StatefulWidget and then add a listener to the focusNode you created and call setState on any events on that focusNode. Otherwise you wont see any changes.
You might want to check out Flutter Cookbook's Focus and text fields recipe.
Essentially, we have to:
FocusNode property.TextFormField.TextFormField.FocusNode property
class CustomTextFormFieldState extends State<CustomTextFormField> {
FocusNode _focusNode;
...
@override
void initState() {
super.initState();
_focusNode = FocusNode();
}
@override
void dispose() {
_focusNode.dispose();
super.dispose();
}
TextFormField
@override
Widget build(BuildContext context) {
return TextFormField(
focusNode: _focusNode,
...
TextFormField
Don't forget to use setState:
void _requestFocus(){
setState(() {
FocusScope.of(context).requestFocus(_focusNode);
});
}
Add the method to the TextFormField's onTap property:
@override
Widget build(BuildContext context) {
return TextFormField(
focusNode: _focusNode,
onTap: _requestFocus,
...
Use themes, this would only have to be done once in a central place:
inputDecorationTheme: InputDecorationTheme(
floatingLabelStyle: TextStyle(color: Colors.blue),
),
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With