【问题标题】:"Null check operator used on a Null Value" in FlutterFlutter 中的“用于 Null 值的 Null 检查运算符”
【发布时间】:2021-09-25 05:55:10
【问题描述】:

我对 Flutter 相当陌生,我正在使用 Firebase 开发一个聊天应用程序。每当我运行应用程序时,我都会面临这个“用于 Null 值的 Null Check 运算符”。这是错误:

    ======== Exception caught by widgets library =======================================================
The following _CastError was thrown building SignIn(dirty, state: _SignInState#ccbd1):
Null check operator used on a null value

The relevant error-causing widget was: 
  SignIn file:///D:/Android/chat_app/lib/helper/authenticate.dart:24:14
When the exception was thrown, this was the stack: 
#0      _SignInState.signIn (package:chat_app/views/signin.dart:32:29)
#1      _SignInState.build (package:chat_app/views/signin.dart:98:28)
#2      StatefulElement.build (package:flutter/src/widgets/framework.dart:4691:27)
#3      ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4574:15)
#4      StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4746:11)
...
====================================================================================================

这是SignIn.dart

    import 'package:chatapp/helper/helperfunctions.dart';
import 'package:chatapp/helper/theme.dart';
import 'package:chatapp/services/auth.dart';
import 'package:chatapp/services/database.dart';
import 'package:chatapp/views/chatrooms.dart';
import 'package:chatapp/views/forgot_password.dart';
import 'package:chatapp/widget/widget.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';

class SignIn extends StatefulWidget {
  final Function toggleView;

  SignIn(this.toggleView);

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

class _SignInState extends State<SignIn> {
  TextEditingController emailEditingController = new TextEditingController();
  TextEditingController passwordEditingController = new TextEditingController();

  AuthService authService = new AuthService();

  final formKey = GlobalKey<FormState>();

  bool isLoading = false;

  signIn() async {
    if (formKey.currentState.validate()) {
      setState(() {
        isLoading = true;
      });

      await authService
          .signInWithEmailAndPassword(
              emailEditingController.text, passwordEditingController.text)
          .then((result) async {
        if (result != null)  {
          QuerySnapshot userInfoSnapshot =
              await DatabaseMethods().getUserInfo(emailEditingController.text);

          HelperFunctions.saveUserLoggedInSharedPreference(true);
          HelperFunctions.saveUserNameSharedPreference(
              userInfoSnapshot.documents[0].data["userName"]);
          HelperFunctions.saveUserEmailSharedPreference(
              userInfoSnapshot.documents[0].data["userEmail"]);

          Navigator.pushReplacement(
              context, MaterialPageRoute(builder: (context) => ChatRoom()));
        } else {
          setState(() {
            isLoading = false;
            //show snackbar
          });
        }
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: appBarMain(context),
      body: isLoading
          ? Container(
              child: Center(child: CircularProgressIndicator()),
            )
          : Container(
              padding: EdgeInsets.symmetric(horizontal: 24),
              child: Column(
                children: [
                  Spacer(),
                  Form(
                    key: formKey,
                    child: Column(
                      children: [
                        TextFormField(
                          validator: (val) {
                            return RegExp(
                                        r"^[a-zA-Z0-9.a-zA-Z0-9.!#$%&'*+-/=?^_`{|}~]+@[a-zA-Z0-9]+\.[a-zA-Z]+")
                                    .hasMatch(val)
                                ? null
                                : "Please Enter Correct Email";
                          },
                          controller: emailEditingController,
                          style: simpleTextStyle(),
                          decoration: textFieldInputDecoration("email"),
                        ),
                        TextFormField(
                          obscureText: true,
                          validator: (val) {
                            return val.length > 6
                                ? null
                                : "Enter Password 6+ characters";
                          },
                          style: simpleTextStyle(),
                          controller: passwordEditingController,
                          decoration: textFieldInputDecoration("password"),
                        ),
                      ],
                    ),
                  ),
                  SizedBox(
                    height: 16,
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.end,
                    children: [
                      GestureDetector(
                        onTap: () {
                          Navigator.push(
                              context,
                              MaterialPageRoute(
                                  builder: (context) => ForgotPassword()));
                        },
                        child: Container(
                            padding: EdgeInsets.symmetric(
                                horizontal: 16, vertical: 8),
                            child: Text(
                              "Forgot Password?",
                              style: simpleTextStyle(),
                            )),
                      )
                    ],
                  ),
                  SizedBox(
                    height: 16,
                  ),
                  GestureDetector(
                    onTap: () {
                      signIn();
                    },
                    child: Container(
                      padding: EdgeInsets.symmetric(vertical: 16),
                      decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(30),
                          gradient: LinearGradient(
                            colors: [
                              const Color(0xff007EF4),
                              const Color(0xff2A75BC)
                            ],
                          )),
                      width: MediaQuery.of(context).size.width,
                      child: Text(
                        "Sign In",
                        style: biggerTextStyle(),
                        textAlign: TextAlign.center,
                      ),
                    ),
                  ),
                  SizedBox(
                    height: 16,
                  ),
                  Container(
                    padding: EdgeInsets.symmetric(vertical: 16),
                    decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(30),
                        color: Colors.white),
                    width: MediaQuery.of(context).size.width,
                    child: Text(
                      "Sign In with Google",
                      style:
                          TextStyle(fontSize: 17, color: CustomTheme.textColor),
                      textAlign: TextAlign.center,
                    ),
                  ),
                  SizedBox(
                    height: 16,
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Text(
                        "Don't have account? ",
                        style: simpleTextStyle(),
                      ),
                      GestureDetector(
                        onTap: () {
                          widget.toggleView();
                        },
                        child: Text(
                          "Register now",
                          style: TextStyle(
                              color: Colors.white,
                              fontSize: 16,
                              decoration: TextDecoration.underline),
                        ),
                      ),
                    ],
                  ),
                  SizedBox(
                    height: 50,
                  )
                ],
              ),
            ),
    );
  }
}

Android Studio 将我重定向到 32:29 的这段代码 ->

 signIn() {
    if (formKey.currentState!.validate()) {

      HelperFunctions.saveUserEmailSharedPreference(emailTextEditingController.text);
      setState(() {
        isLoading = true;
      });

      databaseMethods.getUserByUserEmail(emailTextEditingController.text).then((val) {
        snapShotUserInfo = val;
        HelperFunctions
            .saveUserNameSharedPreference(snapShotUserInfo?.docs[0].data()["name"]);
      });

      
      authMethods.signInWithEmailAndPassword(emailTextEditingController.text, passwordTextEditingController.text)
      .then((val) {
        if (val != null) {

          HelperFunctions.saveUserLoggedInSharedPreference(true);
          Navigator.pushReplacement(context,
              MaterialPageRoute(
                  builder: (context) => ChatRoom())
          );
        }
      });

    }
  }

我们将不胜感激。

【问题讨论】:

  • 你能用调试工具指出错误的确切行吗?
  • 这个错误一直让我回到“if (formKey.currentState!.validate()) {”并且在我调用“signIn()”方法的任何地方都会弹出错误。所以它必须与那个有关..
  • 无法通过查看您的代码找出问题所在,因为它使用了许多外部资源。我发现的一件事是您的颤振版本或 IDE 已过时。由于 null 安全性,最新的 IDE 和颤振会在某些代码上抛出错误。例如在文本框验证和表单验证中
  • 你在用vs代码吗?

标签: android flutter


【解决方案1】:

登录定义使用

QuerySnapshot <dynamic>? snapshotUserInfo;

并用于空值检查

HelperFunctions
        .saveUserNameSharedPreference(snapshotUserInfo!.docs[0].data()["name"]);

【讨论】:

    猜你喜欢
    • 2021-11-06
    • 2021-06-17
    • 2021-12-31
    • 1970-01-01
    • 1970-01-01
    • 2022-08-02
    • 1970-01-01
    • 2022-01-11
    • 2022-01-18
    相关资源
    最近更新 更多