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

Flutter注册功能异常求助:无法注册无提示+InputConnectionAdaptor日志

Flutter注册流程异常:注册失败且错误提示不显示

问题详情

  • 注册流程无法完成,注册失败后身份验证校验的错误提示未正常显示
  • 调试控制台日志(为输入法相关日志,与当前问题无关):
    InputConnectionAdaptor(7041): The input method toggled cursor monitoring on
    InputConnectionAdaptor(7041): The input method toggled cursor monitoring off
    
  • 已尝试操作:将组件改为StatefulWidget,问题仍未解决

相关代码

enum Auth { sigin, signup }

class AuthScreen extends StatefulWidget {
  static const String routeName = '/auth-screen';
  const AuthScreen({super.key});

  @override
  State<AuthScreen> createState() => _AuthScreenState();
}

class _AuthScreenState extends State<AuthScreen> {
  Auth _auth = Auth.signup;
  final _signUpFormKey = GlobalKey<FormState>();
  final _signInFormKey = GlobalKey<FormState>();
  final AuthSevice authSevice = AuthSevice();
  final TextEditingController _emailController = TextEditingController();
  final TextEditingController _passwordController = TextEditingController();
  final TextEditingController _nameController = TextEditingController();

  @override
  void dispose() {
    super.dispose();
    _emailController.dispose();
    _passwordController.dispose();
    _nameController.dispose();
  }

  void signUpUser() {
    authSevice.signUpUser(
      context: context,
      email: _emailController.text,
      password: _passwordController.text,
      name: _nameController.text,
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: GlobalVariables.greyBackgroundCOlor,
      body: SafeArea(
          child: Padding(
        padding: const EdgeInsets.all(8.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text(
              'Welcome',
              style: TextStyle(
                fontSize: 22,
                fontWeight: FontWeight.w500,
              ),
            ),
            ListTile(
              tileColor: _auth == Auth.signup
                  ? GlobalVariables.backgroundColor
                  : GlobalVariables.greyBackgroundCOlor,
              title: const Text(
                'Create Account',
                style: TextStyle(
                  fontWeight: FontWeight.bold,
                ),
              ),
              leading: Radio(
                activeColor: GlobalVariables.secondaryColor,
                value: Auth.signup,
                groupValue: _auth,
                onChanged: (Auth? val) {
                  setState(() {
                    _auth = val!;
                  });
                },
              ),
            ),
            if (_auth == Auth.signup)
              Container(
                padding: const EdgeInsets.all(8.0),
                color: GlobalVariables.backgroundColor,
                child: Form(
                  key: _signUpFormKey,
                  child: Column(
                    children: [
                      CustomTextField(
                        controller: _nameController,
                        hintText: 'Name',
                      ),
                      const SizedBox(
                        height: 10,
                      ),
                      CustomTextField(
                        controller: _emailController,
                        hintText: 'Email',
                      ),
                      const SizedBox(
                        height: 10,
                      ),
                      CustomTextField(
                        controller: _passwordController,
                        hintText: 'Password',
                      ),
                      const SizedBox(
                        height: 10,
                      ),
                      CustomButton(
                          text: 'Sign Up',
                          onTap: () {
                            if (_signInFormKey.currentState!.validate()) {
                              signUpUser();
                            }
                          }),
                    ],
                  ),
                ),
              ),
            ListTile(
              tileColor: _auth == Auth.sigin
                  ? GlobalVariables.backgroundColor
                  : GlobalVariables.greyBackgroundCOlor,
              title: const Text(
                'Sign-In',
                style: TextStyle(
                  fontWeight: FontWeight.bold,
                ),
              ),
              leading: Radio(
                activeColor: GlobalVariables.secondaryColor,
                value: Auth.sigin,
                groupValue: _auth,
                onChanged: (Auth? val) {
                  setState(() {
                    _auth = val!;
                  });
                },
              ),
            ),
            if (_auth == Auth.sigin)
              Container(
                padding: const EdgeInsets.all(8.0),
                color: GlobalVariables.backgroundColor,
                child: Form(
                  key: _signInFormKey,
                  child: Column(
                    children: [
                      CustomTextField(
                        controller: _emailController,
                        hintText: 'Email',
                      ),
                      const SizedBox(
                        height: 10,
                      ),
                      CustomTextField(
                        controller: _passwordController,
                        hintText: 'Password',
                      ),
                      const SizedBox(
                        height: 10,
                      ),
                      CustomButton(text: 'Sign In', onTap: () {}),
                    ],
                  ),
                ),
              ),
          ],
        ),
      )),
    );
  }
}

问题分析与修复步骤

1. 修复表单校验Key错误(核心问题)

注册按钮的点击事件中,错误使用了登录表单的_signInFormKey进行校验,而非注册表单的_signUpFormKey,导致注册表单的校验逻辑完全未执行。

修改注册按钮的onTap代码:

CustomButton(
    text: 'Sign Up',
    onTap: () {
      if (_signUpFormKey.currentState!.validate()) {
        signUpUser();
      }
    }),

2. 确保CustomTextField实现校验逻辑

如果CustomTextField未实现validator回调,表单校验不会生效,错误提示也无法显示。需要给CustomTextField添加校验参数并绑定到TextFormField:

class CustomTextField extends StatelessWidget {
  final TextEditingController controller;
  final String hintText;
  final String? Function(String?)? validator;

  const CustomTextField({
    super.key,
    required this.controller,
    required this.hintText,
    this.validator,
  });

  @override
  Widget build(BuildContext context) {
    return TextFormField(
      controller: controller,
      decoration: InputDecoration(hintText: hintText),
      validator: validator,
    );
  }
}

然后在使用CustomTextField时传入具体的校验规则:

CustomTextField(
  controller: _nameController,
  hintText: 'Name',
  validator: (val) => val?.isEmpty ?? true ? '请输入姓名' : null,
),
CustomTextField(
  controller: _emailController,
  hintText: 'Email',
  validator: (val) {
    if (val?.isEmpty ?? true) return '请输入邮箱';
    final emailRegex = RegExp(r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$');
    return emailRegex.hasMatch(val!) ? null : '请输入有效的邮箱格式';
  },
),
CustomTextField(
  controller: _passwordController,
  hintText: 'Password',
  validator: (val) => (val?.length ?? 0) < 6 ? '密码长度不能少于6位' : null,
),

3. 确保AuthService处理错误提示

检查AuthSevice的signUpUser方法,确保注册失败时通过ScaffoldMessenger展示错误信息:

class AuthSevice {
  void signUpUser({
    required BuildContext context,
    required String email,
    required String password,
    required String name,
  }) async {
    try {
      // 执行注册逻辑(如调用后端API或Firebase Auth等)
    } catch (e) {
      // 展示错误提示
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text(e.toString())),
      );
    }
  }
}

关于控制台日志的说明

控制台输出的InputConnectionAdaptor日志是输入法的正常状态切换,与注册失败及错误提示问题无关,无需处理。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 22:29:50