Loading...
Loading...
Builds Flutter forms with validation and user input handling. Use when creating login screens, data entry forms, or any multi-field user input.
npx skill4agent add flutter/skills flutter-building-formsFormFormStatefulWidgetGlobalKey<FormState>StateGlobalKeybuildGlobalKey<FormState>keyFormFormStateForm.of(context)FormStateTextFormFieldTextFormFieldTextFieldFormFieldvalidator()TextFormFieldStringFormnullStatefulWidgetStatefinal _formKey = GlobalKey<FormState>();StateFormbuildkey: _formKeyTextFormFieldFormvalidatorTextFormFieldStringnullElevatedButtononPressed_formKey.currentState!.validate()_formKey.currentState!.validate()truenullSnackBarfalseFormStatevalidate()trueimport 'package:flutter/material.dart';
class UserRegistrationForm extends StatefulWidget {
const UserRegistrationForm({super.key});
State<UserRegistrationForm> createState() => _UserRegistrationFormState();
}
class _UserRegistrationFormState extends State<UserRegistrationForm> {
// 1. Persist the GlobalKey in the State class
final _formKey = GlobalKey<FormState>();
Widget build(BuildContext context) {
// 2. Bind the key to the Form
return Form(
key: _formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// 3. Add TextFormFields with validators
TextFormField(
decoration: const InputDecoration(
labelText: 'Username',
hintText: 'Enter your username',
),
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter a username'; // Error state
}
if (value.length < 4) {
return 'Username must be at least 4 characters'; // Error state
}
return null; // Valid state
},
),
const SizedBox(height: 16),
// 4. Add the submit button
ElevatedButton(
onPressed: () {
// 5. Trigger validation logic
if (_formKey.currentState!.validate()) {
// Form is valid: Process data
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Processing Data')),
);
} else {
// Form is invalid: Errors are automatically displayed
debugPrint('Form validation failed.');
}
},
child: const Text('Submit'),
),
],
),
);
}
}