Most apps have forms (login, signup, data entry) requiring user input handling and validation. Flutter provides Form, TextFormField, validators, and controllers to build and validate forms — essential for any app with user input.
Form and TextFormField
final _formKey = GlobalKey<FormState>(); // a key to access the form's state
Form(
key: _formKey,
child: Column(children: [
TextFormField(
decoration: InputDecoration(labelText: 'Email'),
validator: (value) { // VALIDATION logic
if (value == null || value.isEmpty) return 'Email required';
if (!value.contains('@')) return 'Invalid email';
return null; // null = valid
},
),
ElevatedButton(
onPressed: () {
if (_formKey.currentState!.validate()) { // run all validators
// all fields valid → submit
}
},
child: Text('Submit'),
),
]),
)
