The Form
widget is to group multiple form fields together.
The default constructor creates a container for form fields.
Form(
key:
child:
)
It contains many input parameters which can be configured to change its behavior and appearance.
The key
parameter is to identify widget.
The child
parameter is to add child widget below Form widget in a tree.
The following code snippet shows how to configure Form
Widget.
final _formKey = GlobalKey<FormState>();
Form(
key: _formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
TextFormField(
decoration: const InputDecoration(
hintText: 'Enter your email',
),
validator: (value) {
if (value.isEmpty) {
return 'Please enter some text';
}
return null;
},
),
Padding(
padding: const EdgeInsets.symmetric(vertical: 16.0),
child: RaisedButton(
onPressed: () {
// Validate will return true if the form is valid, or false if
// the form is invalid.
if (_formKey.currentState.validate()) {
// Process data.
}
},
child: Text('Submit'),
),
),
],
),
);
This example shows a Form
with one TextFormField
to enter an email address and a RaisedButton
to submit the form. A GlobalKey
is used here to identify the Form
and validate input.
import 'package:flutter/material.dart';
class FormDemo extends StatefulWidget {
FormDemo({Key key}) : super(key: key);
_FormDemoState createState() => _FormDemoState();
}
class _FormDemoState extends State<FormDemo> {
final _formKey = GlobalKey<FormState>();
Widget build(BuildContext context) {
return Form(
key: _formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
TextFormField(
decoration: const InputDecoration(
hintText: 'Enter your email',
),
validator: (value) {
if (value.isEmpty) {
return 'Please enter some text';
}
return null;
},
),
Padding(
padding: const EdgeInsets.symmetric(vertical: 16.0),
child: RaisedButton(
onPressed: () {
// Validate will return true if the form is valid, or false if
// the form is invalid.
if (_formKey.currentState.validate()) {
// Process data.
}
},
child: Text('Submit'),
),
),
],
),
);
}
}
class MyApp extends StatelessWidget {
static const String _title = 'Form widget';
Widget build(BuildContext context) {
return MaterialApp(
title: _title,
home: Scaffold(
appBar: AppBar(title: const Text(_title)),
body: FormDemo(),
),
);
}
}
void main() => runApp(MyApp());