Loading...
Loading...
Build a form with validation
npx skill4agent add flutter/skills flutter-formFormTextFormFieldGlobalKey<FormState>_formKey.currentState!.validate()validate()trueSnackBarFormStateTextFormFieldStringvalidatorStatefulWidgetGlobalKey<FormState>Statebuildimport 'package:flutter/material.dart';
class CustomValidatedForm extends StatefulWidget {
const CustomValidatedForm({super.key});
State<CustomValidatedForm> createState() => _CustomValidatedFormState();
}
class _CustomValidatedFormState extends State<CustomValidatedForm> {
// Instantiate the GlobalKey once in the State object
final _formKey = GlobalKey<FormState>();
Widget build(BuildContext context) {
return Form(
key: _formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
// Form fields will be injected here
],
),
);
}
}TextFormFieldFormvalidatorTextFormField(
decoration: const InputDecoration(
hintText: 'Enter your email',
labelText: 'Email',
),
validator: (String? value) {
if (value == null || value.isEmpty) {
return 'Please enter an email address';
}
if (!value.contains('@')) {
return 'Please enter a valid email address';
}
// Return null if the input is valid
return null;
},
onSaved: (String? value) {
// Handle save logic here
},
)FormStateGlobalKeyPadding(
padding: const EdgeInsets.symmetric(vertical: 16.0),
child: ElevatedButton(
onPressed: () {
// Validate returns true if the form is valid, or false otherwise.
if (_formKey.currentState!.validate()) {
// Save the form fields if necessary
_formKey.currentState!.save();
// Provide success feedback
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Processing Data')),
);
}
},
child: const Text('Submit'),
),
)_formKey.currentState!.validate()!validatornull""GlobalKey<FormState>buildStateStatelessWidgetGlobalKeyTextFieldTextFormFieldTextFieldFormFieldnullvalidatorFormTextFormField