Sub topic 14
Showing Server-Side Errors
Assume you know Dart nullable types, closures, StatefulWidget, setState, Form, and TextFormField. This chapter shows how to handle errors that local validation cannot detect.
Local validation and server validation
A validator checks rules that the app can decide immediately. For example, it can check whether an email is empty or has the expected shape. The server must check rules that depend on shared data, such as whether an email address is already registered.
A TextFormField.validator must return a String? synchronously. It cannot wait for a Future. Run the server request in the submit method instead:
- Run local validation.
- Send valid values to the server.
- Store any server error in state.
- Rebuild the form so the error appears.
- Clear the error when the user edits the field.
Displaying a field-specific server error
The example below uses a fake request. A real application would replace _checkEmailWithServer with an HTTP call. The _serverEmailError value belongs to the widget state, so changing it with setState updates the field.
The validator returns the server message after local checks have passed. This lets Flutter display both kinds of errors through the normal TextFormField error area.
import 'package:flutter/material.dart';
void main() {
runApp(const MaterialApp(home: EmailForm()));
}
class EmailForm extends StatefulWidget {
const EmailForm({super.key});
@override
State<EmailForm> createState() => _EmailFormState();
}
class _EmailFormState extends State<EmailForm> {
final _formKey = GlobalKey<FormState>();
final _emailController = TextEditingController();
String? _serverEmailError;
bool _isSubmitting = false;
@override
void dispose() {
_emailController.dispose();
super.dispose();
}
Future<bool> _checkEmailWithServer(String email) async {
await Future<void>.delayed(const Duration(milliseconds: 600));
return email != '[email protected]';
}
Future<void> _submit() async {
setState(() => _serverEmailError = null);
if (!_formKey.currentState!.validate()) return;
setState(() => _isSubmitting = true);
final available =
await _checkEmailWithServer(_emailController.text.trim());
if (!mounted) return;
setState(() {
_isSubmitting = false;
_serverEmailError =
available ? null : 'This email is already registered';
});
if (available) {
debugPrint('Account can be created');
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Create account')),
body: Padding(
padding: const EdgeInsets.all(16),
child: Form(
key: _formKey,
child: Column(
children: [
TextFormField(
controller: _emailController,
keyboardType: TextInputType.emailAddress,
onChanged: (_) {
if (_serverEmailError != null) {
setState(() => _serverEmailError = null);
}
},
decoration: const InputDecoration(labelText: 'Email'),
validator: (value) {
if (value == null || value.trim().isEmpty) {
return 'Email is required';
}
if (!value.contains('@')) {
return 'Enter a valid email address';
}
return _serverEmailError;
},
),
const SizedBox(height: 16),
ElevatedButton(
onPressed: _isSubmitting ? null : _submit,
child: Text(_isSubmitting ? 'Checking...' : 'Continue'),
),
],
),
),
),
);
}
}Common errors and failure handling
Do not leave the submit button active while a request is running. Otherwise, users can send duplicate requests. Disable it with _isSubmitting.
Use mounted after an await. The user may leave the screen while the request is running. Calling setState after disposal causes an error.
Not every server failure belongs to one field. A general response, such as “Service unavailable,” can be shown with a SnackBar, an alert, or a message above the form. Keep server messages safe and suitable for users. Do not display raw exception details or stack traces.
Exercise
Why should the email server error be cleared when the user changes the email?
Show answer
The old response describes the previous value. Clearing it prevents an outdated error from remaining after the user enters new data.