构建带验证的表单
应用通常需要用户在文本字段中输入信息。例如,你可能要求用户使用电子邮件地址和密码组合登录。
为了使应用安全且易于使用,请检查用户提供的信息是否有效。如果用户正确填写了表单,则处理该信息。如果用户提交了不正确的信息,则显示一条友好的错误消息,告知他们出了什么问题。
在此示例中,你将学习如何使用以下步骤为一个包含单个文本字段的表单添加验证:
- 使用
GlobalKey
创建一个Form
。 - 添加一个带验证逻辑的
TextFormField
。 - 创建一个按钮来验证和提交表单。
1. 使用 GlobalKey
创建一个 Form
#创建一个 Form
。Form
widget 充当一个容器,用于分组和验证多个表单字段。
创建表单时,提供一个 GlobalKey
。这会为你的 Form
分配一个唯一标识符。它还允许你稍后验证表单。
将表单创建为 StatefulWidget
。这允许你只创建一次唯一的 GlobalKey<FormState>()
。然后你可以将其存储为变量并在不同点访问它。
如果你将其创建为 StatelessWidget
,则需要将此键存储在*某个地方*。由于它会消耗大量资源,你不会希望每次运行 build
方法时都生成一个新的 GlobalKey
。
import 'package:flutter/material.dart';
// Define a custom Form widget.
class MyCustomForm extends StatefulWidget {
const MyCustomForm({super.key});
@override
MyCustomFormState createState() {
return MyCustomFormState();
}
}
// Define a corresponding State class.
// This class holds data related to the form.
class MyCustomFormState extends State<MyCustomForm> {
// Create a global key that uniquely identifies the Form widget
// and allows validation of the form.
//
// Note: This is a `GlobalKey<FormState>`,
// not a GlobalKey<MyCustomFormState>.
final _formKey = GlobalKey<FormState>();
@override
Widget build(BuildContext context) {
// Build a Form widget using the _formKey created above.
return Form(
key: _formKey,
child: const Column(
children: <Widget>[
// Add TextFormFields and ElevatedButton here.
],
),
);
}
}
2. 添加一个带验证逻辑的 TextFormField
#尽管 Form
已就位,但它没有用户输入文本的方式。这是 TextFormField
的工作。TextFormField
widget 渲染一个 Material Design 文本字段,并可在发生验证错误时显示错误。
通过为 TextFormField
提供一个 validator()
函数来验证输入。如果用户的输入无效,validator
函数将返回一个包含错误消息的 String
。如果没有错误,验证器必须返回 null。
在此示例中,创建一个 validator
以确保 TextFormField
不为空。如果为空,则返回一条友好的错误消息。
TextFormField(
// The validator receives the text that the user has entered.
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter some text';
}
return null;
},
),
3. 创建一个按钮来验证和提交表单
#现在你有一个带文本字段的表单,提供一个按钮,用户可以点击该按钮来提交信息。
当用户尝试提交表单时,检查表单是否有效。如果有效,则显示成功消息。如果无效(文本字段没有内容),则显示错误消息。
ElevatedButton(
onPressed: () {
// Validate returns true if the form is valid, or false otherwise.
if (_formKey.currentState!.validate()) {
// If the form is valid, display a snackbar. In the real world,
// you'd often call a server or save the information in a database.
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Processing Data')),
);
}
},
child: const Text('Submit'),
),
这是如何工作的?
#要验证表单,请使用在步骤 1 中创建的 _formKey
。你可以使用 _formKey.currentState
访问器来访问 FormState
,它由 Flutter 在构建 Form
时自动创建。
FormState
类包含 validate()
方法。当调用 validate()
方法时,它会为表单中的每个文本字段运行 validator()
函数。如果一切正常,validate()
方法将返回 true
。如果任何文本字段包含错误,validate()
方法将重建表单以显示任何错误消息并返回 false
。
互动示例
#import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
const appTitle = 'Form Validation Demo';
return MaterialApp(
title: appTitle,
home: Scaffold(
appBar: AppBar(title: const Text(appTitle)),
body: const MyCustomForm(),
),
);
}
}
// Create a Form widget.
class MyCustomForm extends StatefulWidget {
const MyCustomForm({super.key});
@override
MyCustomFormState createState() {
return MyCustomFormState();
}
}
// Create a corresponding State class.
// This class holds data related to the form.
class MyCustomFormState extends State<MyCustomForm> {
// Create a global key that uniquely identifies the Form widget
// and allows validation of the form.
//
// Note: This is a GlobalKey<FormState>,
// not a GlobalKey<MyCustomFormState>.
final _formKey = GlobalKey<FormState>();
@override
Widget build(BuildContext context) {
// Build a Form widget using the _formKey created above.
return Form(
key: _formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
TextFormField(
// The validator receives the text that the user has entered.
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter some text';
}
return null;
},
),
Padding(
padding: const EdgeInsets.symmetric(vertical: 16),
child: ElevatedButton(
onPressed: () {
// Validate returns true if the form is valid, or false otherwise.
if (_formKey.currentState!.validate()) {
// If the form is valid, display a snackbar. In the real world,
// you'd often call a server or save the information in a database.
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Processing Data')),
);
}
},
child: const Text('Submit'),
),
),
],
),
);
}
}
要了解如何检索这些值,请查看检索文本字段的值烹饪书。