
在上一篇中,我们已经学会了:
但现在有一个现实问题:
❓ 用户什么都没输,也能点“登录”吗? ❓ 密码太短怎么办? ❓ 怎么统一校验所有输入框?
📌 这正是 Form 表单 存在的意义。
在真实 App 中,表单必须做到:
📌 单靠 TextField 是不够的。
Flutter 表单由 三部分 组成:
1️⃣ Form 2️⃣ FormField(通常是 TextFormField) 3️⃣ GlobalKey
Form(
child: Column(
children: [
TextFormField(),
ElevatedButton(
onPressed: () {},
child: Text('提交'),
),
],
),
)
⚠️ 现在这个表单 还不能校验。
final _formKey = GlobalKey<FormState>();
Form(
key: _formKey,
child: ...
)
📌 这个 key 用来:
TextFormField(
decoration: InputDecoration(
hintText: '请输入用户名',
border: OutlineInputBorder(),
),
)
📌 和 TextField 很像,但它支持校验。
TextFormField(
decoration: InputDecoration(
hintText: '请输入用户名',
border: OutlineInputBorder(),
),
validator: (value) {
if (value == null || value.isEmpty) {
return '用户名不能为空';
}
return null;
},
)
📌 规则:
_formKey.currentState!.validate()
ElevatedButton(
onPressed: () {
if (_formKey.currentState!.validate()) {
print('校验通过,提交表单');
}
},
child: Text('登录'),
)
📌 这就是标准表单提交流程。
class LoginPage extends StatefulWidget {
@override
_LoginPageState createState() => _LoginPageState();
}
class _LoginPageState extends State<LoginPage> {
final _formKey = GlobalKey<FormState>();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('登录')),
body: Padding(
padding: EdgeInsets.all(16),
child: Form(
key: _formKey,
child: Column(
children: [
TextFormField(
decoration: InputDecoration(
hintText: '用户名',
border: OutlineInputBorder(),
),
validator: (value) {
if (value == null || value.isEmpty) {
return '请输入用户名';
}
return null;
},
),
SizedBox(height: 16),
TextFormField(
obscureText: true,
decoration: InputDecoration(
hintText: '密码',
border: OutlineInputBorder(),
),
validator: (value) {
if (value == null || value.length < 6) {
return '密码不能少于 6 位';
}
return null;
},
),
SizedBox(height: 24),
ElevatedButton(
onPressed: () {
if (_formKey.currentState!.validate()) {
print('登录成功');
}
},
child: Text('登录'),
),
],
),
),
),
);
}
}
📌 到这里,你已经能写出 完整可用的登录页。
❌ 使用 TextField 而不是 TextFormField ❌ 忘记绑定 Form key ❌ validator 永远返回字符串 ❌ 表单不加 padding ❌ 输入框太多导致溢出(需滚动)
你已经学会:
📌 到这里为止:
你已经具备开发“真实业务页面”的能力
TextField 负责输入 Form 负责校验 GlobalKey 负责控制
《Flutter 零基础入门(三十四):页面跳转 Navigator —— 从一个页面到另一个页面》
下一篇我们将正式进入:
🚀 真正开始“多页面 App 开发”