Issue
I want to change default colour of icon of TextFormField, which will also get changes on selection. There are few way to change colour but non of them works for me.
1. Set icon color
When changing icon colour directly as below the icon colour will not change when selected, below is the code of the same and screenshot which shows red colour when field is selected or not selected.
TextFormField(
maxLength: 15,
decoration: InputDecoration(
labelText: "USER NAME",
prefixIcon: IconTheme(data: IconThemeData(
color: Colors.redAccent
), child: Icon(Icons.email,))
),
onSaved: (username) => _username = username,
),
2. Leave it default
This will show grey colour when field is not selected and primary colour when field is selected. Below is the screenshot of the same. Here i want to change the colour of icon from grey to red and want to show primary colour on selection.
NOTE:- It will be good if we can do this using theme
Solution
The code below will generate the FocusNodes you need to manage the focus of your TextFormFields and do a setState when the focus changes from one field to another. We are just creating a list of focus nodes, listening to changes on each of them and assigning them to a field:
List<FocusNode> _focusNodes = [
FocusNode(),
FocusNode(),
FocusNode(),
FocusNode(),
];
@override
void initState() {
_focusNodes.forEach((node){
node.addListener(() {
setState(() {});
});
});
super.initState();
}
@override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
TextFormField(
focusNode: _focusNodes[0],
decoration: InputDecoration(
prefixIcon: Icon(Icons.email,
color: _focusNodes[0].hasFocus ? Theme.of(context).accentColor : Colors.grey,
),
),
),
TextFormField(
focusNode: _focusNodes[1],
decoration: InputDecoration(
prefixIcon: Icon(Icons.email,
color: _focusNodes[1].hasFocus ? Theme.of(context).accentColor : Colors.grey,
),
),
),
TextFormField(
focusNode: _focusNodes[2],
decoration: InputDecoration(
prefixIcon: Icon(Icons.email,
color: _focusNodes[2].hasFocus ? Theme.of(context).accentColor : Colors.grey,
),
),
),
],
);
}
Answered By - João Soares


0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.