Forms collect user input. Flutter provides TextFormField with built-in validation.
Basic Form
Dart
class ContactForm extends StatefulWidget {
const ContactForm({super.key});
@override
State<ContactForm> createState() => _ContactFormState();
}
class _ContactFormState extends State<ContactForm> {
final _formKey = GlobalKey<FormState>();
@override
Widget build(BuildContext context) {
return Form(
key: _formKey,
child: Column(
children: [
TextFormField(
decoration: InputDecoration(labelText: 'Name'),
validator: (value) =>
value == null || value.isEmpty ? 'Enter a name' : null,
),
TextFormField(
decoration: InputDecoration(labelText: 'Email'),
keyboardType: TextInputType.emailAddress,
validator: (value) {
if (value == null || value.isEmpty) return 'Enter email';
if (!value.contains('@')) return 'Invalid email';
return null;
},
),
ElevatedButton(
onPressed: () {
if (_formKey.currentState!.validate()) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Form submitted!')),
);
}
},
child: Text('Submit'),
),
],
),
);
}
}Tips
- Use
GlobalKey<FormState>to access the form for validation. - Always validate before processing form data.
- Use
TextEditingControllerwhen you need to read the value outsideonChanged.
Next: lists.