'Flutter TextField change Icon color when selected
Goal: Changing the color of the prefixIcon next to the TextField when clicking on the TextField.
TextField(
decoration: InputDecoration(
prefixIcon: Icon(Icons.lock_outline),
hintText: 'Username'
)
)
Solution 1:[1]
As per flutter's update, accentColor property has been deprecated.
https://flutter.dev/docs/release/breaking-changes/theme-data-accent-properties
OLD:
theme: ThemeData(
accentColor: Colors.blue,
),
NEW:
theme: ThemeData(
colorScheme: ThemeData().colorScheme.copyWith(
secondary: Colors.blue,
),
),
Solution 2:[2]
When Selected the color shown is app primaryColor: of Theme.
One Way of changing is using Theme Widget.
Theme(
child: TextField(
decoration: InputDecoration(
prefixIcon: Icon(Icons.email),
labelText: "Email",
hintText: "[email protected]",
),
autofocus: true,
),
data: Theme.of(context)
.copyWith(primaryColor: Colors.redAccent,),
),
Other is to change primaryColor at MaterialApp Theme level.
Solution 3:[3]
In Flutter 2.5, you can set the active color of the icon in ColorScheme.primary:
theme: ThemeData().copyWith(
colorScheme: ThemeData().colorScheme.copyWith(
primary: Colors.green,
),
),
Live Demo
Solution 4:[4]
I was able to achieve that with
ThemeData(
colorScheme: ThemeData().colorScheme.copyWith(
primary:Colors.red,
),
),
inside MaterialApp or you add Theme on your TextFormField
Theme(
data:Theme.of(context).copyWith(
colorScheme: ThemeData().colorScheme.copyWith(
primary:Colors.red,
),
),
child:TextFormField()
)
Solution 5:[5]
Convert StatefulWidget in state class create FocusNodes and use TextFormField
List<FocusNode> _focusNodes = [
FocusNode(),
FocusNode(),
];
@override
void initState() {
_focusNodes.forEach((node){
node.addListener(() {
setState(() {});
});
});
super.initState();
}
TextFormField(
focusNode: _focusNodes[0],
decoration: InputDecoration(
prefixIcon: Icon(
Icons.alternate_email,
color: _focusNodes[0].hasFocus ? Colors.green : Colors.grey,
),
hintText: "Email"),
),
Solution 6:[6]
I was able to accomplish this by modifying the accentColor property at the MaterialApp Theme level.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Shrijan Regmi |
| Solution 2 | anmol.majhail |
| Solution 3 | |
| Solution 4 | Aymen |
| Solution 5 | Çağlar YILMAZ |
| Solution 6 | Lee Mordell |
