Sub topic 14
Showing server-side errors
This chapter assumes you can build a Form with a GlobalKey<FormState>, write TextFormField validators, and use async/await with setState. It covers errors that only the server can detect, such as "this email is already registered". It also covers how to show them in the same place as local validation errors.
Why local validators are not enough
Validators run on the device and must return a result immediately. A validator has the type String? Function(String?), so it cannot be async and cannot wait for a network call. Some rules cannot be checked locally:
- A username or email is already taken.
- A promo code has expired.
- A password fails a policy that lives on the server.
- The server rejects a value your client rules accepted, for example because the two rule sets have drifted apart.
The pattern is the same in every case. Submit the form, wait for the response, store the error in State, and make the field show it.
Storing the error in State
The simplest approach keeps the server message in a nullable field. The validator runs the local rules first and falls back to the stored server message. After a failed request, you set the field and call validate() again so the error text appears.
import 'package:flutter/material.dart';
class ApiValidationException implements Exception {
ApiValidationException(this.fieldErrors);
final Map<String, String> fieldErrors;
}
Future<void> registerUser({required String email}) async {
await Future<void>.delayed(const Duration(seconds: 1));
if (email == '[email protected]') {
throw ApiValidationException({'email': 'This email is already registered'});
}
}
class ServerErrorForm extends StatefulWidget {
const ServerErrorForm({super.key});
@override
State<ServerErrorForm> createState() => _ServerErrorFormState();
}
class _ServerErrorFormState extends State<ServerErrorForm> {
final _formKey = GlobalKey<FormState>();
final _email = TextEditingController();
String? _emailServerError;
bool _submitting = false;
@override
void dispose() {
_email.dispose();
super.dispose();
}
String? _validateEmail(String? value) {
if (value == null || value.trim().isEmpty) return 'Email is required';
if (!value.contains('@')) return 'Enter a valid email address';
return _emailServerError;
}
Future<void> _submit() async {
if (_submitting) return;
_emailServerError = null;
if (!_formKey.currentState!.validate()) return;
setState(() => _submitting = true);
try {
await registerUser(email: _email.text.trim());
if (!mounted) return;
ScaffoldMessenger.of(context)
.showSnackBar(const SnackBar(content: Text('Account created')));
} on ApiValidationException catch (e) {
if (!mounted) return;
_emailServerError = e.fieldErrors['email'];
_formKey.currentState!.validate();
} catch (_) {
if (!mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Something went wrong. Try again.')),
);
} finally {
if (mounted) setState(() => _submitting = false);
}
}
@override
Widget build(BuildContext context) {
return Form(
key: _formKey,
child: Column(
children: [
TextFormField(
controller: _email,
keyboardType: TextInputType.emailAddress,
autovalidateMode: AutovalidateMode.onUserInteraction,
decoration: const InputDecoration(labelText: 'Email'),
validator: _validateEmail,
onChanged: (_) => _emailServerError = null,
),
ElevatedButton(
onPressed: _submitting ? null : _submit,
child: Text(_submitting ? 'Sending...' : 'Sign up'),
),
],
),
);
}
}Several details in this code matter:
_emailServerError = null;runs beforevalidate(). Without it, a stale server message from the last attempt would fail local validation, and the request would never be sent again.- The server message is assigned without
setState. The next call,validate(), updates theFormFieldStateand rebuilds the field itself. onChangedclears the stored message. WithAutovalidateMode.onUserInteraction, the field re-validates on each edit, so the old message disappears as soon as the user types.if (!mounted) return;follows everyawait. The user may have left the screen while the request was running, and usingcontextafter that is a bug.- The
_submittingflag disables the button and guards_submit. This stops double submissions.
Using forceErrorText
Flutter 3.22 added a forceErrorText parameter to TextFormField and FormField. It displays a given message and puts the field in an error state, so you do not need to route the message through the validator.
TextFormField(
controller: _email,
forceErrorText: _emailServerError,
decoration: const InputDecoration(labelText: 'Email'),
validator: (value) =>
(value == null || value.isEmpty) ? 'Email is required' : null,
onChanged: (_) {
if (_emailServerError != null) {
setState(() => _emailServerError = null);
}
},
)Unlike the validator approach, this one needs setState, because the message reaches the field through a widget parameter on rebuild. Check your minimum Flutter version before using it. On older versions, use the validator approach, which works everywhere.
| Approach | Needs `setState` to show | Works before Flutter 3.22 | Message shown by |
|---|---|---|---|
| Validator returns stored message | No, `validate()` redraws the field | Yes | `validate()` call |
| `forceErrorText` | Yes | No | Widget rebuild |
| `errorText` on a plain `TextField` | Yes | Yes | Widget rebuild |
A plain TextField outside a Form has no validator, so there you set InputDecoration.errorText from state directly.
Mapping a server response to fields
Real APIs usually return errors for several fields at once. A common shape is a 422 response such as {"errors": {"email": "...", "password": "..."}}. Parse it into a map at the network layer and keep one map in State.
Map<String, String> _serverErrors = {};
String? _serverError(String field) => _serverErrors[field];
String? _validatePassword(String? value) {
if (value == null || value.isEmpty) return 'Password is required';
return _serverError('password');
}
void _applyServerErrors(Map<String, String> errors) {
_serverErrors = errors;
_formKey.currentState!.validate();
}Each field validator ends with return _serverError('fieldName');. Clear the whole map at the start of each submit, and clear a single key in that field's onChanged.
Not every error belongs to a field. Decide where each kind goes:
| Server problem | Where to show it |
|---|---|
| A named field is invalid | Under that field |
| Several fields are invalid | Under each field, and focus the first one |
| Credentials rejected, account locked | A banner or text above the form |
| Network failure, timeout, 500 | A `SnackBar` with a retry option |
| Field name your form does not have | A banner, so the message is not lost |
The last row is easy to miss. If the server names a field you do not render, a map lookup never finds it and the user sees nothing. Show any unmatched messages in a general banner.
Moving focus to the first error
After a server rejection, the user should land on the problem. Keep a FocusNode for each field and request focus on the first field that has an error. Keep the field order in one list so "first" is predictable.
void _focusFirstError() {
final order = <String, FocusNode>{
'email': _emailFocus,
'password': _passwordFocus,
};
for (final entry in order.entries) {
if (_serverErrors.containsKey(entry.key)) {
entry.value.requestFocus();
return;
}
}
}Call it right after _applyServerErrors. Pass each node to its field with focusNode:, and dispose the nodes in dispose(), as you do for controllers.
Common mistakes
- Leaving the message in place. If the user fixes the email and the old "already registered" text stays, they cannot tell whether their edit worked. Always clear it on change.
- Blocking resubmission. A stored server error that is not cleared before
validate()makes local validation fail forever. - Calling
setStateor usingcontextafterawaitwithout amountedcheck. This throws or logs an error when the widget has been disposed. - Trusting only the client. The server must always validate. Client validators improve usability, and the server is the authority.
- Exposing sensitive detail. Show "Email or password is incorrect", not which half was wrong. Show the server's wording only when it is safe and written for users.
- Showing raw exception text. Map server codes to your own readable messages, which also lets you localize them.
Accessibility of server errors
Error text drawn through InputDecoration is exposed to screen readers as part of the field. A banner or SnackBar is not tied to a field, so write messages that make sense on their own. Moving focus to the first invalid field, as above, also tells keyboard and screen reader users where the problem is.
Exercise
A user submits a form, the server answers that the username is taken, and the field shows the message. The user corrects the username and taps submit again, but the form never sends a request and the old message stays. What is the most likely cause, and how do you fix it?
Show answer
The stored server error was never cleared, so the validator still returns it and validate() fails before the request is sent. Set the stored error to null at the start of the submit method, before calling validate(), and also clear it in the field's onChanged.
Exercise
The server returns {"errors": {"email": "Already used", "nickname": "Too long"}}, but your form has no nickname field. What happens with the stored-map approach, and what should you add?
Show answer
The email message appears under the email field, but the nickname message is never read, so the user sees nothing about it. Collect any keys that do not match a rendered field and show them in a banner or SnackBar.