Form in Flutter with a validator to handle input validation — structured cleanly with best practices.
Source Code
import 'package:flutter/material.dart';
class MyFormExample extends StatefulWidget {
@override
_MyFormExampleState createState() => _MyFormExampleState();
}
class _MyFormExampleState extends State {
final _formKey = GlobalKey();
final TextEditingController _emailController = TextEditingController();
@override
void dispose() {
_emailController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Form with Validator')),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Form(
key: _formKey, // Assign form key
child: Column(
children: [
TextFormField(
controller: _emailController,
decoration: InputDecoration(
labelText: 'Email Address',
border: OutlineInputBorder(),
),
validator: (value) {
if (value == null || value.isEmpty) {
return 'Email is required';
}
if (!RegExp(r'^[\w-\.]+@([\w-]+\.)+[\w]{2,4}').hasMatch(value)) {
return 'Enter a valid email';
}
return null; // input is valid
},
),
SizedBox(height: 20),
ElevatedButton(
onPressed: () {
if (_formKey.currentState!.validate()) {
print('Valid email: ${_emailController.text}');
// Proceed with form submission
}
},
child: Text('Submit'),
),
],
),
),
),
);
}
}
Ai Code Analizer
✅ Key Elements Used
| Element | Purpose |
|---|---|
Form | Parent widget that manages multiple fields and validation. |
GlobalKey<FormState> | Used to reference and validate the form. |
TextFormField | Like TextField but supports built-in validation. |
validator: | Function that returns an error message if input is invalid. |
formKey.currentState!.validate() | Validates all form fields. |
