Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Manually setting Flutter Validation Error

After validating a form and sending a request from flutter to the server backend: I want to set any potential error message from the server to be displayed in the original form. Preferably exactly like a validation error.

For instance:

Widget build(BuildContext context) {
...
  TextFormField(
    onFieldSubmitted: (value) => _signIn(),
    validator: (input) {
      if (input.length < 6)
        return 'Your password is too short';
      return null;
    },
    onSaved: (input) => _password = input,
    decoration: InputDecoration(
      labelText: 'Password',
    ),
    obscureText: true,
  )
...
}

Future<void> _signIn() async {
  final formState = _formKey.currentState;
  if (!formState.validate()) return;
  formState.save();

  try {
    ... // do fancy request stuff
  } catch (e) {
    // this is where I want to set the "validation" error
  }
}
like image 255
EzPizza Avatar asked Oct 04 '19 23:10

EzPizza


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.


1 Answers

It's actually super simple and the validation error still works aswell.

String? _errorMsg;

Widget build(BuildContext context) {
...
  TextFormField(
    onFieldSubmitted: (value) => _signIn(),
    validator: (input) {
      if (input.length < 6)
        // will set the errorText directly, no need for a variable here
        return 'Your password is too short';
      return null;
    },
    onSaved: (input) => _password = input,
    decoration: InputDecoration(
      labelText: 'Password',
      errorText: _errorMsg,
    ),
    obscureText: true,
  )
...
}

Future<void> _signIn() async {
  setState(() {
    _errorMsg = null; // clear any existing errors
  });

  final formState = _formKey.currentState;
  if (!formState.validate()) return;
  formState.save();

  try {
    ... // do fancy request stuff
  } catch (e) {
    setState(() {
      _errorMsg = 'Wrong password.';
    });
  }
}
like image 109
EzPizza Avatar answered Oct 01 '22 09:10

EzPizza