1
Chong Yong Shean
Google Developer Expert - Flutter,
Senior Software Engineer @ Comerge Solutions
Elegant Form Validation in Flutter
2
Agenda
3
Why form validation?
4
Our task today
✅ Ensure user input meets requirements
✅ Show error message below field if not
✅ Only submit form when the form is valid
✅ Show server validation error below field
5
A simple poll + Q&A
Join at
slido.com
#1469 130
6
Basic validation techniques
7
Flutter Form, TextField, TextFormField
Form - for grouping & validating multiple form fields
TextField - for entering text
TextFormField - TextField with validation
slido.com #1469 130
8
Built-in validation methods
Create a Form to contain the TextFormFields and submit button
final _formKey = GlobalKey<FormState>();
Form(
key: _formKey,
child: Column(
children: [...],
),
),
slido.com #1469 130
9
Built-in validation methods
TextFormField’s validator
TextFormField(
// The validator receives the text that the user has entered
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter some text';
}
return null;
},
),
slido.com #1469 130
10
Built-in validation methods
Call _formKey.currentState!.validate() to trigger validation
ElevatedButton(
onPressed: () {
// Validate returns true if the form is valid, or false otherwise.
if (_formKey.currentState!.validate()) {
// If the form is valid, display a snackbar.
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Processing Data')),
);
}
},
child: const Text('Submit'),
),
slido.com #1469 130
11
Result
slido.com #1469 130
12
Control when to validate
13
Validation on submit
Triggers validation whenever the form is submitted.
✅ Done in the previous example
ElevatedButton(
onPressed: () {
// Validate returns true if the form is valid
if (_formKey.currentState!.validate()) {
// If the form is valid, display a snackbar.
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Processing Data')),
);
}
},
child: const Text('Submit'),
),
14
Validation on mount/render
Triggers validation whenever the form is mounted, regardless if the form/field has been changed.
Use AutovalidateMode.always in Form or TextFormField:
Form(
autovalidateMode: AutovalidateMode.always,
child: Column(
children: [
TextFormField(
autovalidateMode: AutovalidateMode.always,
),
],
),
),
15
Validation on change
Triggers validation when any field of the form (or a specific field) has been changed, use AutovalidateMode.onUserInteraction
Form(
autovalidateMode: AutovalidateMode.onUserInteraction,
child: Column(
children: [
TextFormField(
autovalidateMode: AutovalidateMode.onUserInteraction,
),
],
),
),
16
Disable validation
If you want to skip validation, use AutovalidateMode.disabled
Form(
autovalidateMode: AutovalidateMode.disabled,
child: Column(
children: [
TextFormField(
autovalidateMode: AutovalidateMode.disabled,
),
],
),
),
17
Deep Dive into TextFormField
18
TextFormField
decoration: <InputDecoration>
TextFormField(
// decoration is everything you need to “decorate” the field, controls the UI
decoration: InputDecoration(
labelText: 'Password',
suffixIcon: IconButton(...),
filled: true,
fillColor: Colors.black12,
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
),
focusedBorder: ...,
errorStyle: const TextStyle(...),
),
19
TextFormField
textInputAction
TextInputAction.next | To move the cursor to the next field |
TextInputAction.done | To close the keyboard |
20
TextFormField
onChanged: Triggered whenever the field value has changed
TextFormField(
onChanged: (value) {
// you can obtain the current value from here
setState(() => username = value);
// or reset the async validation error state
setIsUsernameAlreadyTaken(false);
},
),
21
TextFormField
onSaved: Triggered whenever formKey.currentState.save() is called
TextFormField(
onSaved: (value) {
// save the validated value to the state
setState(() => username = value);
},
),
22
Handling complex validation scenarios
23
github.com/yshean/form_validation_demo
Use for a URL or a CTA
24
When to use TextField?
25
You don’t want to nest it under Form.
If you only have one field, or you don’t need the validation, then TextField is 👍.
26
You want to manage validations on your own.
If you like to keep your view clean and delegate every form logic to a controller or bloc, then TextField is 👍.
27
But… everything is more verbose (harder 😓) with TextField
TextField does not include validation.
We need to DIY validation by defining onChanged, focusNode, controller, etc.
28
General idea of how to do validation with TextField
29
Example: Validation on blur (with TextField)
Triggers validation when a field is unfocused
We need FocusNode:
30
Key takeaways
31
Key takeaways
✅ Use Form & TextFormField whenever you can
✅ Use TextField only for very simple cases
✅ Use InputDecoration for customising text editing area
✅ Combine TextFormField’s validator with local states for a non-Material/Cupertino look
32
linkedin.com/in/yshean
Comerge Solutions is hiring! We are an international team based in Zürich and Kuala Lumpur who are proud to produce software you like.
Talk to me for more info:)
https://blog.logrocket.com/flutter-form-validation-complete-guide -> Making a custom form field
https://github.com/yshean/form_validation_demo