flutter-building-forms
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseBuilding Validated Forms
构建带验证功能的表单
Contents
目录
Form Architecture
表单架构
Implement forms using a widget to group and validate multiple input fields together.
Form- Use a StatefulWidget: Always host your inside a
Form.StatefulWidget - Persist the GlobalKey: Instantiate a exactly once as a final variable within the
GlobalKey<FormState>class. Do not generate a newStateinside theGlobalKeymethod; doing so is resource-expensive and destroys the form's state on every rebuild.build - Bind the Key: Pass the to the
GlobalKey<FormState>property of thekeywidget. This uniquely identifies the form and provides access to theFormfor validation and submission.FormState - Alternative Access: If dealing with highly complex widget trees where passing the key is impractical, use to access the
Form.of(context)from a descendant widget.FormState
使用组件来构建表单,将多个输入字段分组并统一验证。
Form- 使用StatefulWidget: 始终将放置在
Form中。StatefulWidget - 持久化GlobalKey: 在类中仅实例化一次
State并设为final变量。不要在GlobalKey<FormState>方法中生成新的build,这会耗费资源并在每次重建时销毁表单状态。GlobalKey - 绑定Key: 将传递给
GlobalKey<FormState>组件的Form属性。这会为表单分配唯一标识,并提供访问key的入口以进行验证和提交操作。FormState - 替代访问方式: 如果在复杂的组件树中传递Key不切实际,可以使用从子组件中访问
Form.of(context)。FormState
Field Validation
字段验证
Use to render Material Design text inputs with built-in validation support. is a convenience widget that automatically wraps a standard inside a .
TextFormFieldTextFormFieldTextFieldFormField- Implement the Validator: Provide a callback function to each
validator().TextFormField - Return Error Messages: If the user's input is invalid, return a containing the specific error message. The
Stringwill automatically rebuild to display this text below the field.Form - Return Null for Success: If the input passes validation, you must return .
null
使用来渲染Material Design风格的文本输入框,它内置了验证支持。是一个便捷组件,会自动将标准包装在中。
TextFormFieldTextFormFieldTextFieldFormField- 实现验证器: 为每个提供
TextFormField回调函数。validator() - 返回错误信息: 如果用户输入无效,返回包含具体错误信息的字符串。会自动重建UI,在字段下方显示该文本。
Form - 验证通过返回Null: 如果输入通过验证,必须返回。
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 and its corresponding
StatefulWidgetclass.State - 2. Instantiate in the
final _formKey = GlobalKey<FormState>();class.State - 3. Return a widget in the
Formmethod and assignbuild.key: _formKey - 4. Add widgets as descendants of the
TextFormField.Form - 5. Write a function for each
validator(returnTextFormFieldon error,Stringon success).null - 6. Add a submit button (e.g., ).
ElevatedButton - 7. Implement the validation check in the button's callback using
onPressed._formKey.currentState!.validate()
遵循以下顺序流程来实现并验证表单。可复制此检查列表跟踪进度。
任务进度:
- 1. 创建一个及其对应的
StatefulWidget类。State - 2. 在类中实例化
State。final _formKey = GlobalKey<FormState>(); - 3. 在方法中返回
build组件,并设置Form。key: _formKey - 4. 在的子组件中添加
Form。TextFormField - 5. 为每个编写
TextFormField函数(错误时返回字符串,验证通过时返回validator)。null - 6. 添加提交按钮(如)。
ElevatedButton - 7. 在按钮的回调中使用
onPressed实现验证检查。_formKey.currentState!.validate()
Validation Decision Logic
验证决策逻辑
When the user triggers the submit action, execute the following conditional logic:
- Call .
_formKey.currentState!.validate() - If (Valid): All validators returned
true. Proceed with form submission (e.g., save data, make API call) and display a success indicator (e.g., anull).SnackBar - If (Invalid): One or more validators returned an error string. The
falseautomatically rebuilds the UI to display the error messages.FormState - Feedback Loop: Run validator -> review errors -> fix. The user must adjust their input and resubmit until returns
validate().true
当用户触发提交操作时,执行以下条件逻辑:
- 调用。
_formKey.currentState!.validate() - 如果返回true(验证通过): 所有验证器都返回了。继续执行表单提交(如保存数据、调用API)并显示成功提示(如
null)。SnackBar - 如果返回false(验证失败): 一个或多个验证器返回了错误字符串。会自动重建UI以显示错误信息。
FormState - 反馈循环: 运行验证器 -> 查看错误 -> 修正输入。用户必须调整输入并重新提交,直到返回
validate()。true
Examples
示例
Complete Validated Form Implementation
完整的带验证功能表单实现
Use the following pattern to implement a robust, validated form.
dart
import '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'),
),
],
),
);
}
}使用以下模式来实现一个健壮的带验证功能的表单。
dart
import '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'),
),
],
),
);
}
}