flutter-building-forms

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

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
    Form
    inside a
    StatefulWidget
    .
  • Persist the GlobalKey: Instantiate a
    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.
  • Bind the Key: Pass the
    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.
  • Alternative Access: If dealing with highly complex widget trees where passing the key is impractical, use
    Form.of(context)
    to access the
    FormState
    from a descendant widget.
使用
Form
组件来构建表单,将多个输入字段分组并统一验证。
  • 使用StatefulWidget: 始终将
    Form
    放置在
    StatefulWidget
    中。
  • 持久化GlobalKey:
    State
    类中仅实例化一次
    GlobalKey<FormState>
    并设为final变量。不要在
    build
    方法中生成新的
    GlobalKey
    ,这会耗费资源并在每次重建时销毁表单状态。
  • 绑定Key:
    GlobalKey<FormState>
    传递给
    Form
    组件的
    key
    属性。这会为表单分配唯一标识,并提供访问
    FormState
    的入口以进行验证和提交操作。
  • 替代访问方式: 如果在复杂的组件树中传递Key不切实际,可以使用
    Form.of(context)
    从子组件中访问
    FormState

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 each
    TextFormField
    .
  • Return Error Messages: If the user's input is invalid, return a
    String
    containing the specific error message. The
    Form
    will automatically rebuild to display this text below the field.
  • Return Null for Success: If the input passes validation, you must return
    null
    .
使用
TextFormField
来渲染Material Design风格的文本输入框,它内置了验证支持。
TextFormField
是一个便捷组件,会自动将标准
TextField
包装在
FormField
中。
  • 实现验证器: 为每个
    TextFormField
    提供
    validator()
    回调函数。
  • 返回错误信息: 如果用户输入无效,返回包含具体错误信息的字符串。
    Form
    会自动重建UI,在字段下方显示该文本。
  • 验证通过返回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
    StatefulWidget
    and its corresponding
    State
    class.
  • 2. Instantiate
    final _formKey = GlobalKey<FormState>();
    in the
    State
    class.
  • 3. Return a
    Form
    widget in the
    build
    method and assign
    key: _formKey
    .
  • 4. Add
    TextFormField
    widgets as descendants of the
    Form
    .
  • 5. Write a
    validator
    function for each
    TextFormField
    (return
    String
    on error,
    null
    on success).
  • 6. Add a submit button (e.g.,
    ElevatedButton
    ).
  • 7. Implement the validation check in the button's
    onPressed
    callback using
    _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:
  1. Call
    _formKey.currentState!.validate()
    .
  2. If
    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
    ).
  3. If
    false
    (Invalid):
    One or more validators returned an error string. The
    FormState
    automatically rebuilds the UI to display the error messages.
  4. Feedback Loop: Run validator -> review errors -> fix. The user must adjust their input and resubmit until
    validate()
    returns
    true
    .
当用户触发提交操作时,执行以下条件逻辑:
  1. 调用
    _formKey.currentState!.validate()
  2. 如果返回true(验证通过): 所有验证器都返回了
    null
    。继续执行表单提交(如保存数据、调用API)并显示成功提示(如
    SnackBar
    )。
  3. 如果返回false(验证失败): 一个或多个验证器返回了错误字符串。
    FormState
    会自动重建UI以显示错误信息。
  4. 反馈循环: 运行验证器 -> 查看错误 -> 修正输入。用户必须调整输入并重新提交,直到
    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'),
          ),
        ],
      ),
    );
  }
}