Flutter
The Form widget
Group multiple fields with the Form widget.
Form widget
The Form widget groups multiple form fields and provides a common validation/saving mechanism. Every TextFormField placed inside a Form is managed in a single form context.
Form(
key: _formKey,
child: Column(
children: [TextFormField(...)],
),
)
This way you can check all fields from a single place.
key and GlobalKey
You give a Form a key of type GlobalKey<FormState>. Through this key you access the form's state and call validate and save methods.
final _formKey = GlobalKey<FormState>();
Form(
key: _formKey,
child: ...,
)
Without a key you cannot reach the form's state.
Exercise Group fields with Form
In Ekrani stateful widget, declare a GlobalKey<FormState> named _formKey. In initState, call print('form ekranı'). In build, place a Form with a TextFormField inside. Bind _formKey to the Form.
Show example solution
import 'package:flutter/material.dart';
void main() => runApp(MaterialApp(home: Ekrani()));
class Ekrani extends StatefulWidget {
@override
_EkraniState createState() => _EkraniState();
}
class _EkraniState extends State<Ekrani> {
final _formKey = GlobalKey<FormState>();
@override
void initState() {
super.initState();
print('form ekranı');
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Form')),
body: Padding(
padding: EdgeInsets.all(16),
child: Form(
key: _formKey,
child: Column(
children: [
TextFormField(
decoration: InputDecoration(labelText: 'İsim'),
),
],
),
),
),
);
}
}
Test yourself
-
What is the main purpose of the Form widget?
- To set the background color
- To perform database operations
- To group multiple form fields and provide common validation
- To manage page transitions
Show answer
To group multiple form fields and provide common validation — The Form widget groups multiple form fields under a single context; this way validate and save operations can be done at once.
-
Give the Form the GlobalKey type
final _formKey = GlobalKey<____>();
Form(key: _formKey, child: ...)
Show answer
final _formKey = GlobalKey<FormState>();
Form(key: _formKey, child: ...)
-
Form parts
- Form
- Widget grouping form fields
- GlobalKey<FormState>
- Key providing access to form state
- TextFormField
- Field widget used inside Form
- key
- Parameter giving form state access
Next lesson: validator