user14598625
user14598625

Reputation:

How to change label text color of FormTextField when error

How to automatically change label text color of TextFormField in flutter?

Upvotes: 0

Views: 2050

Answers (1)

M.mhr
M.mhr

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

Related Questions