F
flutter-building-forms
by @flutterv
4.5(28)
用于构建带有验证和用户输入处理功能的Flutter表单。此技能帮助开发者创建交互性强、数据准确的移动应用界面,提升用户体验和数据质量。
安装方式
npx skills add flutter/skills --skill flutter-building-formscompare_arrows
Before / After 效果对比
1 组使用前
Flutter表单构建复杂,用户输入处理和验证逻辑繁琐。开发效率低下,容易出现错误,影响用户数据提交体验。
使用后
轻松构建带验证和用户输入处理的Flutter表单。显著提升了表单开发效率,确保数据准确性,优化了用户交互体验。
SKILL.md
Building Validated Forms
Contents
Form Architecture
Implement forms using a Form widget to group and validate multiple input fields together.
- Use a StatefulWidget: Always host your
Forminside aStatefulWidget. - Persist the GlobalKey: Instantiate a
GlobalKey<FormState>exactly once as a final variable within theStateclass. Do not generate a newGlobalKeyinside thebuildmethod; doing so is resource-expensive and destroys the form's state on every rebuild. - Bind the Key: Pass the
GlobalKey<FormState>to thekeyproperty of theFormwidget. This uniquely identifies the form and provides access to theFormStatefor validation and submission. - Alternative Access: If dealing with highly complex widget trees where passing the key is impractical, use
Form.of(context)to access theFormStatefrom a descendant widget.
Field Validation
Use TextFormField to render Material Design text inputs with built-in validation support. TextFormField is a convenience widget that automatically wraps a standard TextField inside a FormField.
- Implement the Validator: Provide a
validator()callback function to eachTextFormField. - Return Error Messages: If the user's input is invalid, return a
Stringcontaining the specific error message. TheFormwill automatically rebuild to display this text below the field. - Return Null for Success: If the input passes validation, you must return
null.
Workflow: Implementing a Validated Form
Follow this sequential workflow to implement and validate a form. Copy the checklist to track your progress.
Task Progress:
- 1. Create a
StatefulWidgetand its correspondingStateclass. - 2. Instantiate
final _formKey = GlobalKey<FormState>();in theStateclass. - 3. Return a
Formwidget in thebuildmethod and assignkey: _formKey. - 4. Add
TextFormFieldwidgets as descendants of theForm. - 5. Write a
validatorfunction for eachTextFormField(returnStringon error,nullon success). - 6. Add a submit button (e.g.,
ElevatedButton). - 7. Implement the validation check in the button's
onPressedcallback using_formKey.currentState!.validate().
Validation Decision Logic
When the user triggers the submit action, execute the following conditional logic:
- Call
_formKey.currentState!.validate(). - If
true(Valid): All validators returnednull. Proceed with form submission (e.g., save data, make API call) and display a success indicator (e.g., aSnackBar). - If
false(Invalid): One or more validators returned an error string. TheFormStateautomatically rebuilds the UI to display the error messages. - Feedback Loop: Run validator -> review errors -> fix. The user must adjust their input and resubmit until
validate()returnstrue.
Examples
Complete Validated Form Implementation
Use the following pattern to implement a robust, validated form.
import 'package:flutter/material.dart';
class UserRegistrationForm extends StatefulWidget {
const UserRegistrationForm({super.key});
@override
State<UserRegistrationForm> createState() => _UserRegistrationFormState();
}
class _UserRegistrationFormState extends State<UserRegistrationForm> {
// 1. Persist the GlobalKey in the State class
final _formKey = GlobalKey<FormState>();
@override
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'),
),
],
),
);
}
}
用户评价 (0)
发表评价
效果
易用性
文档
兼容性
暂无评价
统计数据
安装量8.6K
评分4.5 / 5.0
版本
更新日期2026年5月9日
对比案例1 组
用户评分
4.5(28)
5
14%
4
46%
3
36%
2
4%
1
0%
为此 Skill 评分
0.0
兼容平台
🔧Claude Code
🔧OpenClaw
🔧OpenCode
🔧Codex
🔧Gemini CLI
🔧GitHub Copilot
🔧Amp
🔧Kimi CLI
时间线
创建2026年3月16日
最后更新2026年5月9日