Flutter注册表单:Checkbox无法勾选与TextFormField校验失效问题
注册表单问题修复
问题根因
- Checkbox状态无法切换:
agree变量定义在build方法内部,每次setState触发组件重建时,变量会被重新初始化为false,状态永远无法更新。 - 表单校验不生效:
Form组件未绑定全局校验Key,无触发校验的入口- 多数输入框未配置
validator规则 - 提交按钮点击逻辑未调用校验方法,无法触发错误提示
- 输入框未绑定值存储逻辑,校验通过后无法获取用户输入
修复后完整代码
import 'dart:developer'; import 'package:flutter/gestures.dart'; import 'package:flutter/services.dart'; import 'package:flutter/material.dart'; import 'package:email_validator/email_validator.dart'; class SignUp extends StatefulWidget { @override _SignUpState createState() => _SignUpState(); } class _SignUpState extends State<SignUp> { // 全局表单Key 用于触发校验 final _formKey = GlobalKey<FormState>(); // 状态变量移到类成员位置 避免被build重置 bool _agree = false; String? _firstname; String? _lastname; String? _username; String? _email; String? _mobileno; String? _password; void _doSomething() { // 校验通过后提交逻辑 if (_formKey.currentState!.validate()) { _formKey.currentState!.save(); log('注册信息: $_firstname, $_lastname, $_username, $_email, $_mobileno'); } } @override Widget build(BuildContext context) { var screenSize = MediaQuery.of(context).size; return Container( width: screenSize.width, decoration: const BoxDecoration( image: DecorationImage( image: AssetImage("assets/img/bg_signup.png"), fit: BoxFit.cover, ), ), child: SingleChildScrollView( child: Form( key: _formKey, // 绑定全局Key child: Column( children: [ // FirstName 输入框 加非空校验 Padding( padding: const EdgeInsets.fromLTRB(30, 10, 30, 0), child: TextFormField( keyboardType: TextInputType.text, decoration: const InputDecoration( labelText: "First Name", labelStyle: TextStyle( fontFamily: 'Poppins', fontWeight: FontWeight.w300, ), fillColor: Colors.white, border: OutlineInputBorder( borderRadius: BorderRadius.all(Radius.circular(10.0)), borderSide: BorderSide(color: Colors.blue), ), ), style: const TextStyle( fontFamily: 'Poppins', fontWeight: FontWeight.w300, ), // 非空校验 validator: (value) { if (value == null || value.isEmpty) { return 'First Name 不能为空'; } return null; }, // 保存输入值 onSaved: (value) => _firstname = value, ), ), // LastName 输入框 加非空校验 Padding( padding: const EdgeInsets.fromLTRB(30, 25, 30, 0), child: TextFormField( keyboardType: TextInputType.text, decoration: const InputDecoration( labelText: "Last Name", labelStyle: TextStyle( fontFamily: 'Poppins', fontWeight: FontWeight.w300, ), fillColor: Colors.white, border: OutlineInputBorder( borderRadius: BorderRadius.all(Radius.circular(10.0)), borderSide: BorderSide(color: Colors.blue), ), ), style: const TextStyle( fontFamily: 'Poppins', fontWeight: FontWeight.w300, ), validator: (value) { if (value == null || value.isEmpty) { return 'Last Name 不能为空'; } return null; }, onSaved: (value) => _lastname = value, ), ), // Username 输入框 Padding( padding: const EdgeInsets.fromLTRB(30, 25, 30, 0), child: TextFormField( decoration: const InputDecoration( labelText: "Username", labelStyle: TextStyle( fontFamily: 'Poppins', fontWeight: FontWeight.w300, ), fillColor: Colors.white, border: OutlineInputBorder( borderRadius: BorderRadius.all(Radius.circular(10.0)), borderSide: BorderSide(color: Colors.blue), ), ), style: const TextStyle( fontFamily: 'Poppins', fontWeight: FontWeight.w300, ), onSaved: (value) => _username = value, ), ), // Email 输入框 保留原有校验 Padding( padding: const EdgeInsets.fromLTRB(30, 25, 30, 0), child: TextFormField( decoration: const InputDecoration( labelText: "Email", labelStyle: TextStyle( fontFamily: 'Poppins', fontWeight: FontWeight.w300, ), fillColor: Colors.white, border: OutlineInputBorder( borderRadius: BorderRadius.all(Radius.circular(10.0)), borderSide: BorderSide(color: Colors.blue), ), ), validator: (value) => EmailValidator.validate(value ?? '') ? null : "请输入合法的Email地址", style: const TextStyle( fontFamily: 'Poppins', fontWeight: FontWeight.w300, ), onSaved: (value) => _email = value, ), ), // 手机号 输入框 加格式校验 Padding( padding: const EdgeInsets.fromLTRB(30, 25, 30, 0), child: TextFormField( keyboardType: TextInputType.number, inputFormatters: [FilteringTextInputFormatter.digitsOnly], decoration: const InputDecoration( labelText: "Mobile Number", labelStyle: TextStyle( fontFamily: 'Poppins', fontWeight: FontWeight.w300, ), fillColor: Colors.white, border: OutlineInputBorder( borderRadius: BorderRadius.all(Radius.circular(10.0)), borderSide: BorderSide(color: Colors.blue), ), ), style: const TextStyle( fontFamily: 'Poppins', fontWeight: FontWeight.w300, ), // 手机号校验 示例为11位大陆手机号 可根据需求调整 validator: (value) { if (value == null || value.isEmpty) { return '手机号不能为空'; } if (!RegExp(r'^1[3-9]\d{9}$').hasMatch(value)) { return '请输入合法的11位手机号'; } return null; }, onSaved: (value) => _mobileno = value, ), ), // 密码 输入框 加规则校验 Padding( padding: const EdgeInsets.fromLTRB(30, 25, 30, 0), child: TextFormField( obscureText: true, decoration: const InputDecoration( labelText: "Password", labelStyle: TextStyle( fontFamily: 'Poppins', fontWeight: FontWeight.w300, ), fillColor: Colors.white, border: OutlineInputBorder( borderRadius: BorderRadius.all(Radius.circular(10.0)), borderSide: BorderSide(color: Colors.blue), ), ), style: const TextStyle( fontFamily: 'Poppins', fontWeight: FontWeight.w300, ), // 密码规则校验 示例为最少6位 包含字母和数字 可根据需求调整 validator: (value) { if (value == null || value.isEmpty) { return '密码不能为空'; } if (!RegExp(r'^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,}$') .hasMatch(value)) { return '密码需至少6位,包含字母和数字'; } _password = value; return null; }, ), ), // 确认密码 输入框 加一致性校验 Padding( padding: const EdgeInsets.fromLTRB(30, 25, 30, 0), child: TextFormField( obscureText: true, decoration: const InputDecoration( labelText: "Confirm Password", labelStyle: TextStyle( fontFamily: 'Poppins', fontWeight: FontWeight.w300, ), fillColor: Colors.white, border: OutlineInputBorder( borderRadius: BorderRadius.all(Radius.circular(10.0)), borderSide: BorderSide(color: Colors.blue), ), ), style: const TextStyle( fontFamily: 'Poppins', fontWeight: FontWeight.w300, ), validator: (value) { if (value != _password) { return '两次输入的密码不一致'; } return null; }, ), ), // 协议勾选行 Row( children: [ Checkbox( checkColor: Colors.red, focusColor: Colors.black, value: _agree, onChanged: (bool? value) { setState(() { _agree = value ?? false; }); }, ), Expanded( child: RichText( text: TextSpan( children: [ const TextSpan( text: 'Accept the ', style: TextStyle(color: Colors.black), ), TextSpan( text: 'terms and conditions', style: const TextStyle( color: Colors.blue, fontWeight: FontWeight.bold, ), recognizer: TapGestureRecognizer() ..onTap = () { // 修复原逻辑未调用showDialog的问题 showDialog( context: context, builder: (context) => AlertDialog( title: const Text('提示'), content: const Text('这是用户协议弹窗'), actions: [ TextButton( onPressed: () => Navigator.pop(context), child: const Text('确认'), ) ], ), ); }, ), ], ), ), ), ], ), // 提交按钮 勾选协议后可点击 点击触发校验 Padding( padding: const EdgeInsets.symmetric(vertical: 20), child: ElevatedButton( onPressed: _agree ? _doSomething : null, child: const Text('Continue'), ), ) ], ), ), ), ); } }
关键修复点说明
- Checkbox状态:将
_agree变量从build方法内移到State类的成员位置,setState更新时不会被重置 - 表单校验:
- 给
Form组件绑定_formKey全局Key - 所有需要校验的输入框均配置对应
validator规则 - 提交按钮点击逻辑中调用
validate()触发校验,校验通过后才执行提交逻辑 - 输入框配置
onSaved方法存储有效输入值
- 给
- 顺带修复了原代码中点击用户协议无弹窗、手机号输入可输入非数字字符的问题
内容的提问来源于stack exchange,提问作者pramod patel
相关产品推荐
相关产品推荐

