Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reset error message in TextFormField?

Tags:

flutter

dart

I know this is a simple question but i did not find how to do this. How can i reset error message in TextFormField when the user input something in the field. Something like onchange listener. I notice onChanged is available in TextField but not TextFormField. How can i do this?

final _email = Container(
  child: TextFormField(
    decoration: InputDecoration(labelText: email),
    keyboardType: TextInputType.emailAddress,
    controller: emailController,
    validator: _validateEmail,
    onSaved: (input) => _stringEmail = input.toLowerCase().trim(),
  ),
);

UPDATE: I am using controller to add listener for user input. But i just want to reset the error message instead of validating the form again. Is this possible? How can i do this?

  _resetEmailErrorMessage() {
    print("Second text field: ${emailController.text}");
    //replace clear to something that can reset the validation error message
    emailController.clear();
  }

  @override
  void initState() {
    super.initState();

    //start listening to changes
    emailController.addListener(_resetEmailErrorMessage);
  }
like image 522
MRu Avatar asked Aug 20 '19 13:08

MRu


People also ask

How do you change the position of validation error in flutter forms?

You need to put TextFormField and Container with box decoration in a stack. Now when validator will show error message then container with not grow and gives an impression that error message is showing below TextFormField.

What is error text in flutter?

errorText property Null safetyText that appears below the InputDecorator. child and the border. If non-null, the border's color animates to red and the helperText is not shown. In a TextFormField, this is overridden by the value returned from TextFormField. validator, if that is not null.


1 Answers

You can use auto-validation feature of Form

If you looking for this solution,

"As soon as you type it validates your input and show/hide error"

Flutter provides auto-validation feature, you just need to enable it at form level.

  1. Default

    _autoValidate = false;

  2. Form

    body: Form( key: _formKey,
                autovalidate: _autoValidate,....)
  1. Enable it when user presses submit once,
    if (_formKey.currentState.validate()) {
      // All Good
    } else {
      // start auto validate
      setState(() {
        _autoValidate = true;
      });
    }

Update :-

Now Form.autovalidate is deprecated. So Use

Form.autovalidateMode = AutovalidateMode.onUserInteraction 
like image 182
Ankit Mahadik Avatar answered Oct 20 '22 20:10

Ankit Mahadik