【问题标题】:Exception while trying to validate a TextFormField Input尝试验证 TextFormField 输入时出现异常
【发布时间】:2022-01-22 04:53:05
【问题描述】:

我正在尝试在我的项目中验证两个TextFormFields(电子邮件和密码)。但是在验证TextFormField 时出现异常。有人可以让我知道我哪里出错了吗?或者如何修复错误。

我得到的错误是:════════ Exception caught by gesture ═══════════════════════════════════════════ Null check operator used on a null value ════════════════════════════════════════════════════════════════════════════════

我的代码:

class _LoginState extends State<Login> {
  @override
  Widget build(BuildContext context) {
    final _formKey = GlobalKey<FormState>();

    TextEditingController emailController;
    TextEditingController passwordController;
    final authService = Provider.of<AuthService>(context);
    emailController = TextEditingController();
    passwordController = TextEditingController();
    return Scaffold(
      backgroundColor: Colors.white,
      body: SingleChildScrollView(
          child: Column(children: <Widget>[
        Padding(
          padding: const EdgeInsets.only(top: 60.0),
          child: Center(
            child: Container(
                width: 300,
                height: 380,
                decoration:
                    BoxDecoration(borderRadius: BorderRadius.circular(50.0)),
                child: Image.asset(
                  'assets/images/logo.png',
                )),
          ),
        ),
        const SizedBox(height: 15.0),
        Padding(
          padding: EdgeInsets.only(left: 25.0, right: 25.0, top: 0, bottom: 0),
          child: TextFormField(
            validator: (value) {
              if (value == null || value.isEmpty) {
                return 'Please enter the email.';
              }
              return null;
            },
            controller: emailController,
            decoration: InputDecoration(
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(60),
                ),
                prefixIcon: const Icon(Icons.mail),
                labelText: 'E-Mail',
                hintText: 'admin@gmail.com'),
          ),
        ),
        Padding(
          padding: EdgeInsets.only(left: 25.0, right: 25.0, top: 15, bottom: 0),
          child: TextFormField(
            validator: (value) {
              if (value == null || value.isEmpty) {
                return 'Please enter the password.';
              }
              return null;
            },
            controller: passwordController,
            obscureText: true,
            decoration: InputDecoration(
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(60),
                ),
                prefixIcon: const Icon(Icons.vpn_key),
                labelText: 'Password',
                hintText: 'Enter your Password'),
          ),
        ),
        const SizedBox(
          height: 100,
        ),
        TextButton(
            onPressed: () {
              if (_formKey.currentState!.validate()) {
                ScaffoldMessenger.of(context).showSnackBar(
                  const SnackBar(content: Text('Processing')),
                );
              }
              authService.signInWithEmailAndPassword(context,
                  emailController.text.trim(), passwordController.text.trim());
            },
            child: const Text(
              'Login',
              textAlign: TextAlign.center,
            )),
        MaterialButton(
            onPressed: () {
              Navigator.push(context,
                  MaterialPageRoute(builder: (context) => forgotPassword()));
            },
            child: Text(
              'Forgot Password',
              textAlign: TextAlign.center,
              style: TextStyle(fontSize: 13.0, color: Colors.red.shade900),
            ))
      ])),
    );
  }
}

提前谢谢你。

【问题讨论】:

    标签: flutter validation dart exception


    【解决方案1】:

    在您的 sn-p 中没有使用 _formKeyForm 小部件,这就是它从 _formKey.currentState!.validate() 抛出错误的原因。因为您使用的是!,它说currentState of formKey 永远不会为空。

    你可以先检查空状态来处理它。

     TextButton(
                 onPressed: () {
                   if (_formKey.currentState == null) {
                     return; // dont execute rest code
                   }
                   if (_formKey.currentState!.validate()) {
                     ScaffoldMessenger.of(context).showSnackBar(
                       const SnackBar(content: Text('Processing')),
                     );
                   authService.signInWithEmailAndPassword(context, 
                  emailController.text.trim(),
                   passwordController.text.trim());
                   },
    

    Form 小部件放在Column 小部件之前。

       body: SingleChildScrollView(
              child: Form(
            key: _formKey,
            child: Column(children: <Widget>[
              Padding(
                padding: const EdgeInsets.only(top: 60.0),
                child: Center(
    

    更多关于forms validation

    【讨论】:

    • 验证现在有效,但现在登录无效。我无法登录应用程序。我在if 语句中附加了authService.signInWithEmailAndPassword( context, emailController.text.trim(), passwordController.text.trim());。登录失败的任何原因?
    • 条件语句在范围之外,它也在未经验证的情况下运行我认为signInWithEmailAndPassword未来,然后制作async方法并在authService之前使用await
    • 这是一个很好的example 或者可能是登录问题
    【解决方案2】:

    您导致此错误是因为您在代码中定义了 _formkey 但未定义 used,因此它没有任何 valueState 现在您必须包装您的 TextFormField Form小部件中,需要传递定义的key,可以查看下面的代码

    final _formKey = GlobalKey<FormState>();
    
    class _LoginState extends State<Login> {
      @override
      Widget build(BuildContext context) {
    
        TextEditingController emailController;
        TextEditingController passwordController;
        final authService = Provider.of<AuthService>(context);
        emailController = TextEditingController();
        passwordController = TextEditingController();
        return Scaffold(
          backgroundColor: Colors.white,
          body: SingleChildScrollView(
              child: Column(children: <Widget>[
                Padding(
                  padding: const EdgeInsets.only(top: 60.0),
                  child: Center(
                    child: Container(
                        width: 300,
                        height: 380,
                        decoration:
                        BoxDecoration(borderRadius: BorderRadius.circular(50.0)),
                        child: Image.asset(
                          'assets/images/logo.png',
                        )),
                  ),
                ),
                const SizedBox(height: 15.0),
                Form(
                  key: _formKey,
                  child: Padding(
                    padding: EdgeInsets.only(left: 25.0, right: 25.0, top: 0, bottom: 0),
                    child: TextFormField(
                      validator: (value) {
                        if (value == null || value.isEmpty) {
                          return 'Please enter the email.';
                        }
                        return null;
                      },
                      controller: emailController,
                      decoration: InputDecoration(
                          border: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(60),
                          ),
                          prefixIcon: const Icon(Icons.mail),
                          labelText: 'E-Mail',
                          hintText: 'admin@gmail.com'),
                    ),
                  ),
                ),
                Padding(
                  padding: EdgeInsets.only(left: 25.0, right: 25.0, top: 15, bottom: 0),
                  child: TextFormField(
                    validator: (value) {
                      if (value == null || value.isEmpty) {
                        return 'Please enter the password.';
                      }
                      return null;
                    },
                    controller: passwordController,
                    obscureText: true,
                    decoration: InputDecoration(
                        border: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(60),
                        ),
                        prefixIcon: const Icon(Icons.vpn_key),
                        labelText: 'Password',
                        hintText: 'Enter your Password'),
                  ),
                ),
                const SizedBox(
                  height: 100,
                ),
                TextButton(
                    onPressed: () {
                      if (_formKey.currentState!.validate()) {
                        ScaffoldMessenger.of(context).showSnackBar(
                          const SnackBar(content: Text('Processing')),
                        );
                      }
                      authService.signInWithEmailAndPassword(context,
                          emailController.text.trim(), passwordController.text.trim());
                    },
                    child: const Text(
                      'Login',
                      textAlign: TextAlign.center,
                    )),
                MaterialButton(
                    onPressed: () {
                      Navigator.push(context,
                          MaterialPageRoute(builder: (context) => forgotPassword()));
                    },
                    child: Text(
                      'Forgot Password',
                      textAlign: TextAlign.center,
                      style: TextStyle(fontSize: 13.0, color: Colors.red.shade900),
                    ))
              ])),
        );
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-17
      • 1970-01-01
      • 2018-04-30
      相关资源
      最近更新 更多