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

Flutter验证邮箱密码出现_CastError(Null check operator used on a null value)如何解决

错误原因

你触发_CastError (Null check operator used on a null value)的核心原因是:你声明了表单全局key_formKey,但没有将其绑定到Form组件上,导致调用_formKey.currentState时返回值为null,你后续使用!空断言运算符强制取值就触发了类型转换错误。

修复方案

仅需修改一处代码:在你的Form组件上添加key: _formKey属性即可。
你也可以对登录按钮的点击逻辑做安全优化,避免极端场景下的异常:把_formKey.currentState!.validate()改成_formKey.currentState?.validate() == true,去掉强制非空断言。

修正后完整代码

import 'package:flutter/material.dart';

class Login extends StatefulWidget {
  const Login({Key? key}) : super(key: key);

  @override
  _LoginState createState() => _LoginState();
}

class _LoginState extends State<Login> {
  final _formKey = GlobalKey<FormState>();
  var email = "";
  var password = "";

  final emailController = TextEditingController();
  final passwordController = TextEditingController();

  @override
  void dispose() {
    emailController.dispose();
    passwordController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Form(
      // 新增绑定key的代码
      key: _formKey,
      child: Padding(
        padding: const EdgeInsets.all(20.0),
        child: ListView(
          children: [
            Container(
              margin: const EdgeInsets.symmetric(vertical: 10),
              child: TextFormField(
                controller: emailController,
                autofocus: false,
                decoration: const InputDecoration(
                  labelText: "Email: ",
                  labelStyle: TextStyle(
                    fontSize: 20,
                  ),
                  border: OutlineInputBorder(),
                  errorStyle: TextStyle(fontSize: 15, color: Colors.redAccent),
                ),
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return "Please Enter Email";
                  }
                  if (!value.contains("@")) {
                    return "Please Enter Valid Email ";
                  }
                  return null;
                },
              ),
            ),
            Container(
              margin: const EdgeInsets.symmetric(vertical: 10),
              child: TextFormField(
                controller: passwordController,
                autofocus: false,
                decoration: const InputDecoration(
                  labelText: "Password: ",
                  labelStyle: TextStyle(
                    fontSize: 20,
                  ),
                  border: OutlineInputBorder(),
                  errorStyle: TextStyle(fontSize: 15, color: Colors.redAccent),
                ),
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return "Please Enter Password";
                  }
                  return null;
                },
                keyboardType: TextInputType.number,
                obscureText: true,
              ),
            ),
            Container(
              margin: const EdgeInsets.symmetric(vertical: 20),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  ElevatedButton(
                    onPressed: () {
                      // 优化后的判空逻辑,避免强制非空断言
                      if (_formKey.currentState?.validate() == true) {
                        setState(() {
                          email = emailController.text;
                          password = passwordController.text;
                        });
                      }
                    },
                    child: const Text("LOGIN"),
                  ),
                  TextButton(
                    onPressed: () {},
                    child: const Text(
                      "Forgot Password",
                      style: TextStyle(fontSize: 14),
                    ),
                  ),
                ],
              ),
            ),
            Container(
              margin: const EdgeInsets.symmetric(vertical: 1),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  const Text("Don't Have An Account?"),
                  TextButton(
                    onPressed: () {},
                    child: const Text("Sign-Up"),
                  )
                ],
              ),
            )
          ],
        ),
      ),
    ));
  }
}

内容的提问来源于stack exchange,提问作者Rudransh Singh Mahra

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 18:15:03