Flutter
autovalidateMode
Validate on the fly with autovalidateMode.
What is autovalidateMode?
autovalidateMode determines when the form runs the validator. It takes three values: disabled (off), always (always) and onUserInteraction (on user interaction).
Form(
autovalidateMode: AutovalidateMode.always,
child: ...,
)
This way error messages are shown instantly.
always and onUserInteraction
AutovalidateMode.always runs the validator every time the form is built. AutovalidateMode.onUserInteraction starts running after the user changes a field.
Form(
autovalidateMode: AutovalidateMode.onUserInteraction,
child: ...,
)
always is more aggressive, onUserInteraction is more user-friendly.
Exercise Instant validation with autovalidateMode
In Ekrani stateful widget, declare _formKey. Give the Form autovalidateMode: AutovalidateMode.always. Place a TextFormField inside; the validator should return 'Boş' for empty value. In main, call print('form açıldı').
Show example solution
import 'package:flutter/material.dart';
void main() {
print('form açıldı');
runApp(MaterialApp(home: Ekrani()));
}
class Ekrani extends StatefulWidget {
@override
_EkraniState createState() => _EkraniState();
}
class _EkraniState extends State<Ekrani> {
final _formKey = GlobalKey<FormState>();
@override
Widget build(BuildContext context) {
return Scaffold(
body: Padding(
padding: EdgeInsets.all(16),
child: Form(
key: _formKey,
autovalidateMode: AutovalidateMode.always,
child: Column(
children: [
TextFormField(
validator: (deger) {
if (deger!.isEmpty) {
return 'Boş';
}
return null;
},
),
],
),
),
),
);
}
}
Test yourself
-
When does autovalidateMode.onUserInteraction run the validator?
- Never runs
- After the user touches the field, on every change
- Only on page open
- Only when the button is pressed
Show answer
After the user touches the field, on every change — onUserInteraction runs the validator on every change after the user first touches the field; this gives instant feedback.
-
Set autovalidateMode to always
Form(
autovalidateMode: AutovalidateMode.____,
child: ...,
)
Show answer
Form(
autovalidateMode: AutovalidateMode.always,
child: ...,
)
-
autovalidateMode parts
- autovalidateMode
- Determines when validator runs
- always
- Validator runs on every build
- onUserInteraction
- Runs after user touches
- disabled
- Validator is off
Next lesson: Summary - Form validation