flutter-building-forms by flutter/skills
npx skills add https://github.com/flutter/skills --skill flutter-building-forms使用 Form 小部件来实现表单,以便将多个输入字段分组并进行统一验证。
Form 放在一个 StatefulWidget 内部。State 类中,将 GlobalKey<FormState> 作为 final 变量精确地实例化一次。不要在 build 方法内部生成新的 GlobalKey;这样做会消耗大量资源,并在每次重建时销毁表单的状态。广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
GlobalKey<FormState>FormkeyFormStateForm.of(context) 从后代小部件访问 FormState。使用 TextFormField 来渲染具有内置验证支持的 Material Design 文本输入框。TextFormField 是一个便捷的小部件,它自动将标准的 TextField 包装在一个 FormField 中。
TextFormField 提供一个 validator() 回调函数。String。Form 将自动重建,以在字段下方显示此文本。null。遵循这个顺序工作流程来实现和验证表单。复制检查清单以跟踪你的进度。
任务进度:
StatefulWidget 及其对应的 State 类。State 类中实例化 final _formKey = GlobalKey<FormState>();。build 方法中返回一个 Form 小部件,并分配 key: _formKey。TextFormField 小部件作为 Form 的后代添加。TextFormField 编写一个 validator 函数(错误时返回 String,成功时返回 null)。ElevatedButton)。onPressed 回调中使用 _formKey.currentState!.validate() 实现验证检查。当用户触发提交操作时,执行以下条件逻辑:
_formKey.currentState!.validate()。true(有效): 所有验证器都返回了 null。继续表单提交(例如,保存数据,进行 API 调用)并显示成功指示器(例如,一个 SnackBar)。false(无效): 一个或多个验证器返回了错误字符串。FormState 会自动重建 UI 以显示错误信息。validate() 返回 true。使用以下模式来实现一个健壮的验证表单。
import 'package:flutter/material.dart';
class UserRegistrationForm extends StatefulWidget {
const UserRegistrationForm({super.key});
@override
State<UserRegistrationForm> createState() => _UserRegistrationFormState();
}
class _UserRegistrationFormState extends State<UserRegistrationForm> {
// 1. 在 State 类中持久化 GlobalKey
final _formKey = GlobalKey<FormState>();
@override
Widget build(BuildContext context) {
// 2. 将 key 绑定到 Form
return Form(
key: _formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// 3. 添加带有验证器的 TextFormFields
TextFormField(
decoration: const InputDecoration(
labelText: '用户名',
hintText: '输入你的用户名',
),
validator: (value) {
if (value == null || value.isEmpty) {
return '请输入用户名'; // 错误状态
}
if (value.length < 4) {
return '用户名必须至少 4 个字符'; // 错误状态
}
return null; // 有效状态
},
),
const SizedBox(height: 16),
// 4. 添加提交按钮
ElevatedButton(
onPressed: () {
// 5. 触发验证逻辑
if (_formKey.currentState!.validate()) {
// 表单有效:处理数据
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('正在处理数据')),
);
} else {
// 表单无效:错误信息会自动显示
debugPrint('表单验证失败。');
}
},
child: const Text('提交'),
),
],
),
);
}
}
每周安装量
1.8K
代码仓库
GitHub 星标
792
首次出现
11 天前
安全审计
安装于
codex1.7K
gemini-cli1.7K
opencode1.7K
github-copilot1.7K
kimi-cli1.7K
cursor1.7K
Implement forms using a Form widget to group and validate multiple input fields together.
Form inside a StatefulWidget.GlobalKey<FormState> exactly once as a final variable within the State class. Do not generate a new GlobalKey inside the build method; doing so is resource-expensive and destroys the form's state on every rebuild.GlobalKey<FormState> to the key property of the Form widget. This uniquely identifies the form and provides access to the FormState for validation and submission.Form.of(context) to access the FormState from a descendant widget.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.
validator() callback function to each TextFormField.String containing the specific error message. The Form will automatically rebuild to display this text below the field.null.Follow this sequential workflow to implement and validate a form. Copy the checklist to track your progress.
Task Progress:
StatefulWidget and its corresponding State class.final _formKey = GlobalKey<FormState>(); in the State class.Form widget in the build method and assign key: _formKey.TextFormField widgets as descendants of the Form.validator function for each TextFormField (return on error, on success).When the user triggers the submit action, execute the following conditional logic:
_formKey.currentState!.validate().true (Valid): All validators returned null. Proceed with form submission (e.g., save data, make API call) and display a success indicator (e.g., a SnackBar).false (Invalid): One or more validators returned an error string. The FormState automatically rebuilds the UI to display the error messages.validate() returns true.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'),
),
],
),
);
}
}
Weekly Installs
1.8K
Repository
GitHub Stars
792
First Seen
11 days ago
Security Audits
Gen Agent Trust HubPassSocketPassSnykPass
Installed on
codex1.7K
gemini-cli1.7K
opencode1.7K
github-copilot1.7K
kimi-cli1.7K
cursor1.7K
React 组合模式指南:Vercel 组件架构最佳实践,提升代码可维护性
102,200 周安装
StringnullElevatedButton).onPressed callback using _formKey.currentState!.validate().