Flutter
onSaved
Collect form data with the onSaved callback.
What is onSaved?
onSaved is a callback given to a TextFormField. It is called when the form is saved, letting you take the field's value and store it in a variable.
String? _name;
TextFormField(
onSaved: (value) {
_name = value;
},
)
onSaved is triggered when the save method is called.
FormState.save
When _formKey.currentState!.save() is called, the onSaved callback of every TextFormField in the form runs. This way you transfer all field values to variables.
String? _name;
String? _email;
if (_formKey.currentState!.validate()) {
_formKey.currentState!.save();
print('Name: $_name');
}
save is called after validate succeeds.
Exercise Collect data with onSaved
In Ekrani stateful widget, declare _formKey and _isim variable. Place a TextFormField inside a Form; with onSaved assign the value to _isim. On button press, if validate succeeds, call save and print 'isim: $_isim'. In main, call print('form başladı').
Show example solution
import 'package:flutter/material.dart';
void main() {
print('form başladı');
runApp(MaterialApp(home: Ekrani()));
}
class Ekrani extends StatefulWidget {
@override
_EkraniState createState() => _EkraniState();
}
class _EkraniState extends State<Ekrani> {
final _formKey = GlobalKey<FormState>();
String? _isim;
@override
Widget build(BuildContext context) {
return Scaffold(
body: Padding(
padding: EdgeInsets.all(16),
child: Form(
key: _formKey,
child: Column(
children: [
TextFormField(
onSaved: (deger) {
_isim = deger;
},
),
ElevatedButton(
onPressed: () {
if (_formKey.currentState!.validate()) {
_formKey.currentState!.save();
print('isim: $_isim');
}
},
child: Text('Kaydet'),
),
],
),
),
),
);
}
}
Test yourself
-
When is the onSaved callback called?
- Every time the user presses a key
- When the form is built
- When the form's save method is called
- Only in initState
Show answer
When the form's save method is called — The onSaved callback is triggered for each TextFormField when FormState.save is called; this way field values are collected.
-
Add the FormState.save call
if (_formKey.currentState!.validate()) {
_formKey.currentState!.____();
print('kaydedildi');
}
Show answer
if (_formKey.currentState!.validate()) {
_formKey.currentState!.save();
print('kaydedildi');
}
-
onSaved parts
- onSaved
- Callback to collect field value
- save
- Method triggering all onSaved
- FormState
- State where save is called
- validate
- Validation done before save
Next lesson: autovalidateMode