flutter-form by flutter/skills
npx skills add https://github.com/flutter/skills --skill flutter-form在 Flutter 中使用 Form、TextFormField 和 GlobalKey<FormState> 实现有状态的表单验证。高效管理验证状态,避免不必要的键值重新生成,并处理用户输入验证工作流。假设已存在一个包含 Material Design 依赖项的 Flutter 环境。
实现表单验证时,请遵循以下决策树来确定状态和 UI 更新的流程:
_formKey.currentState!.validate()。validate() 是否返回 true?
SnackBar、导航)。广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
FormState 会自动重建 TextFormField 小部件,以显示其各自的 validator 函数返回的 String 错误消息。停止提交。初始化有状态表单容器 创建一个 StatefulWidget 来容纳表单。在 State 类中精确地实例化一次 GlobalKey<FormState>,以防止在 build 周期中重新生成消耗资源的键值。
import 'package:flutter/material.dart';
class CustomValidatedForm extends StatefulWidget {
const CustomValidatedForm({super.key});
@override
State<CustomValidatedForm> createState() => _CustomValidatedFormState();
}
class _CustomValidatedFormState extends State<CustomValidatedForm> {
// 在 State 对象中实例化 GlobalKey 一次
final _formKey = GlobalKey<FormState>();
@override
Widget build(BuildContext context) {
return Form(
key: _formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
// 表单字段将在此处注入
],
),
);
}
}
实现带有验证逻辑的 TextFormFields 将 TextFormField 小部件注入到 Form 的小部件树中。为每个字段提供一个 validator 函数。
TextFormField(
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';
}
// 如果输入有效,则返回 null
return null;
},
onSaved: (String? value) {
// 在此处处理保存逻辑
},
)
实现提交操作和验证触发器 创建一个按钮,通过 GlobalKey 访问 FormState 以触发验证。
Padding(
padding: const EdgeInsets.symmetric(vertical: 16.0),
child: ElevatedButton(
onPressed: () {
// 如果表单有效,validate 返回 true,否则返回 false。
if (_formKey.currentState!.validate()) {
// 如有必要,保存表单字段
_formKey.currentState!.save();
// 提供成功反馈
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Processing Data')),
);
}
},
child: const Text('Submit'),
),
)
暂停并询问用户: 暂停实现,并向用户询问以下上下文信息:
验证与修复循环 生成表单后,验证以下内容:
!) 或安全调用对 _formKey.currentState!.validate() 进行了正确的空值检查,以防键值可能已分离。validator 函数在成功时是否显式返回 null。返回空字符串 ("") 将触发一个没有文本的错误状态。build 方法内部实例化 GlobalKey<FormState>。它必须是 State 类的持久成员。StatelessWidget,除非 GlobalKey 是从一个有状态的父组件传递下来的。TextField 小部件;必须使用 TextFormField(它在 FormField 中包装了 TextField)。validator 函数返回 null。Form 小部件是所有需要一起验证的 TextFormField 小部件的共同祖先。每周安装量
135
代码仓库
GitHub 星标数
808
首次出现
2026年3月11日
安全审计
安装于
codex127
gemini-cli125
amp125
cline125
github-copilot125
opencode125
Implements stateful form validation in Flutter using Form, TextFormField, and GlobalKey<FormState>. Manages validation state efficiently without unnecessary key regeneration and handles user input validation workflows. Assumes a pre-existing Flutter environment with Material Design dependencies available.
When implementing form validation, follow this decision tree to determine the flow of state and UI updates:
_formKey.currentState!.validate().validate() return true?
SnackBar, navigation).FormState automatically rebuilds the TextFormField widgets to display the String error messages returned by their respective validator functions. Halt submission.Initialize the Stateful Form Container Create a StatefulWidget to hold the form. Instantiate a GlobalKey<FormState> exactly once within the State class to prevent resource-expensive key regeneration during build cycles.
import 'package:flutter/material.dart';
class CustomValidatedForm extends StatefulWidget {
const CustomValidatedForm({super.key});
@override
State<CustomValidatedForm> createState() => _CustomValidatedFormState();
}
class _CustomValidatedFormState extends State<CustomValidatedForm> {
// Instantiate the GlobalKey once in the State object
final _formKey = GlobalKey<FormState>();
@override
Widget build(BuildContext context) {
return Form(
key: _formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
// Form fields will be injected here
],
),
);
}
}
Implement TextFormFields with Validation Logic Inject widgets into the 's widget tree. Provide a function for each field.
GlobalKey<FormState> inside the build method. It must be a persistent member of the State class.StatelessWidget for the form container unless the GlobalKey is being passed down from a stateful parent.TextField widgets if you require built-in form validation; you must use TextFormField (which wraps TextField in a FormField).Weekly Installs
135
Repository
GitHub Stars
808
First Seen
Mar 11, 2026
Security Audits
Gen Agent Trust HubPassSocketPassSnykPass
Installed on
codex127
gemini-cli125
amp125
cline125
github-copilot125
opencode125
Flutter 主屏幕小组件开发指南:iOS/Android 原生小组件集成与数据通信
3,300 周安装
Web应用测试指南:使用Python Playwright自动化测试本地Web应用
40,900 周安装
前端打磨(Polish)终极指南:提升产品细节与用户体验的系统化检查清单
42,800 周安装
Excel财务建模规范与xlsx文件处理指南:专业格式、零错误公式与数据分析
44,500 周安装
Azure虚拟机推荐工具:根据工作负载自动推荐最佳VM规格和VMSS配置
47,600 周安装
DOCX文件创建、编辑与分析完整指南 - 使用docx-js、Pandoc和Python脚本
49,200 周安装
simple头脑风暴技能:轻量级结构化协作工具,快速将想法转化为行动方案
51,100 周安装
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
},
)
Implement the Submit Action and Validation Trigger Create a button that accesses the FormState via the GlobalKey to trigger validation.
Padding(
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'),
),
)
STOP AND ASK THE USER: Pause implementation and ask the user for the following context:
Validate-and-Fix Loop After generating the form, verify the following:
_formKey.currentState!.validate() is null-checked properly using the bang operator (!) or safe calls if the key might be detached.validator function explicitly returns null on success. Returning an empty string ("") will trigger an error state with no text.nullvalidatorForm widget is a common ancestor to all TextFormField widgets that need to be validated together.