You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中StatefulWidget表单提交时用户名/密码/邮箱为null的解决方法

问题原因及解决方法

你的代码存在两个核心问题,导致点击注册后Profile的字段始终为null:

1. Form组件未绑定GlobalKey

你创建了formKey但没有将其赋值给Form组件的key属性,这会导致formKey.currentState一直为null,调用formKey.currentState?.save()时根本无法触发任何TextFormField的onSaved回调。

2. TextFormField的onSaved中错误递归调用form.save()

在邮箱和用户名对应的TextFormField的onSaved回调里,你额外调用了formKey.currentState?.save(),这属于无效且错误的递归操作——onSaved本身就是在调用form.save()时被系统自动触发的回调,完全不需要手动再次调用。


修改后的完整代码

class _RegisterScreenState extends State<RegisterScreen> {
  final formKey = GlobalKey<FormState>();
  Profile profile = Profile();

  @override
  Widget build(BuildContext context) {
    // 给Form绑定key,关联GlobalKey
    return Form(
      key: formKey,
      child: Scaffold(
        body: Container(
          margin: EdgeInsets.all(24),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: [
              // _header(context),
              _inputField(context),
              // _forgotPassword(context),
            ],
          ),
        ),
      ),
    );
  }

  _inputField(context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: [
        TextFormField(
          keyboardType: TextInputType.emailAddress,
          onSaved: (String? email) {
            // 移除错误的form.save()调用,直接给profile赋值
            profile.email = email;
          },
          // 可选:添加验证确保输入不为空
          validator: (value) => value?.isEmpty ?? true ? '请输入邮箱' : null,
        ),
        SizedBox(height: 10),
        TextFormField(
          onSaved: (String? username) {
            // 移除错误的form.save()调用,直接给profile赋值
            profile.username = username;
          },
          validator: (value) => value?.isEmpty ?? true ? '请输入用户名' : null,
        ),
        SizedBox(height: 10),
        TextFormField(
          obscureText: true, // 密码框建议添加隐藏文本
          onSaved: (String? password) {
            profile.password = password;
          },
          validator: (value) => value?.isEmpty ?? true ? '请输入密码' : null,
        ),
        SizedBox(height: 10),
        ElevatedButton(
          onPressed: () {
            // 先验证表单合法性,再执行保存和跳转
            if (formKey.currentState?.validate() ?? false) {
              formKey.currentState?.save();
              print(
                  "email =${profile.email} username =${profile.username} password =${profile.password}");
              Navigator.push(context, MaterialPageRoute(builder: ((context) {
                return LoginScreen();
              })));
            }
          },
          child: Text("Register"),
        )
      ],
    );
  }
}

额外优化建议

  • 给密码输入框添加obscureText: true,提升账号安全性
  • 增加表单验证逻辑,确保用户输入不为空再执行后续操作

内容的提问来源于stack exchange,提问作者JInSeok

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 11:50:23