Reputation:
How to automatically change label text color of TextFormField
in flutter?
Upvotes: 0
Views: 2050
Reputation: 1749
Try this:
class MyViewState extends State<MyView> {
bool _invalidValue = false;
...
TextFormField(
autovalidateMode: AutovalidateMode.always,
decoration: InputDecoration(
icon: const Icon(Icons.person),
hintText: 'What is your name?',
labelText: 'Name',
labelStyle:
TextStyle(color: _invalidValue ? Colors.red : Colors.blue),
),
validator: (String? value) {
final b = (value != null && value.contains('@'));
SchedulerBinding.instance!.addPostFrameCallback((timestamp) {
if (_invalidValue != b) {
setState(() {
_invalidValue = b;
});
}
});
return b ? 'Do not use the @ char.' : null;
},
)
The b
variable is for preventing setState
to be called every time, only when needed
Upvotes: 1