Reputation: 489
I have a name form field in flutter app. There's a prefix icon in it. When I click the form field the color of icon changes to blue, rather I want to change it to green. How can I do that, can anyone please guide me? This is its code :
TextFormField(
decoration: InputDecoration(
focusedBorder: OutlineInputBorder(
borderSide: const BorderSide(color: Colors.green, width: 2.0),
borderRadius: BorderRadius.circular(10.0),
),
prefixIcon: const Icon(Icons.person),
hintText: "Name",
border: OutlineInputBorder(borderRadius: BorderRadius.circular(10)),
),
);
Upvotes: 0
Views: 1803
Reputation: 119
This is an updated version of Flutter 3.22
prefixIconColor: WidgetStateColor.resolveWith(
(Set<WidgetState> states) {
if (states.contains(WidgetState.focused)) {
return Colors.blue; // Cor quando focado
}
return Colors.grey; // Cor padrão
},
),
Upvotes: 0
Reputation: 191
You can set the default color for selection such as textfield border or prefix icon of the same using colorScheme
MaterialApp(theme: ThemeData(
colorScheme: ThemeData().colorScheme.copyWith(primary: kPrimaryColor),
)
Upvotes: 0
Reputation: 3552
Flutter's way to go is to use resolveWith. You can check the current state to check if the text field is focused, shows an error, etc. And depending on that you set the color.
From the docs (https://api.flutter.dev/flutter/material/InputDecoration-class.html):
final ThemeData themeData = Theme.of(context);
return Theme(
data: themeData.copyWith(
inputDecorationTheme: themeData.inputDecorationTheme.copyWith(
prefixIconColor:
MaterialStateColor.resolveWith((Set<MaterialState> states) {
if (states.contains(MaterialState.focused)) {
return Colors.green;
}
if (states.contains(MaterialState.error)) {
return Colors.red;
}
return Colors.grey;
}),
)),
child: TextFormField(
initialValue: 'abc',
decoration: const InputDecoration(
prefixIcon: Icon(Icons.person),
),
),
);
Upvotes: 2
Reputation: 1427
Use Theme
color to change then define the focus node to determine when the field is on focus in order to apply these color changes
...
FocusNode _fieldNode = FocusNode(); //<-Define this then
...
TextFormField(
decoration: InputDecoration(
focusedBorder: OutlineInputBorder(
borderSide: const BorderSide(color: Colors.green, width: 2.0),
borderRadius: BorderRadius.circular(10.0),
),
prefixIcon: Icon(Icons.person,
color: _fieldNode.hasFocus
? Theme.of(context).primaryColor
: Colors.purple)),
hintText: "Name",
border: OutlineInputBorder(borderRadius: BorderRadius.circular(10)),
),
);
Upvotes: 1