使用 getX 注销时在空值上使用空检查运算符

Null check operator used on a null value when logout using getX

因此,登录时一切顺利,但在注销时抛出 _CastError,即使注销进行得很好,但我担心这个错误会在生产模式中造成问题。

这是我的代码 auth_model

Rxn<User> _user = Rxn<User>() ;


 String? get user => _user.value!.email;

 @override
 void onInit() {
  // TODO: implement onInit
   super.onInit();
   _user.bindStream(_auth.authStateChanges());
  }

这是我的 controller_view

的代码
 return Obx((){
  return(Get.find<AuthViewModel>().user != null)
      ? HomeScreen()
      : Home();
});

这个来自我的 homeScreen

class HomeScreen extends StatelessWidget {
    FirebaseAuth _auth = FirebaseAuth.instance;

  @override
  Widget build(BuildContext context) {
    return Scaffold(

      appBar: AppBar(
        title: Text(
          "Home Screen",
              textAlign: TextAlign.center,
        ),
      ),
      body: Column(
        children: <Widget>[
          Center(
            child: TextButton(
              child: Text(
                  "logout"
              ),
              onPressed: () {
                _auth.signOut();
                Get.offAll(Home());
              },
            ),
          ),
        ],
      ),
    );
  }
}

如有任何帮助,我将不胜感激。

这就是问题所在。

/// You tried to declare a private variable that might be `null`.
/// All `Rxn` will be null by default.
Rxn<User> _user = Rxn<User>();

/// You wanted to get a String from `email` property... from that variable.
/// But you also want to return `null` if it doesn't exist. see: `String?` at the beginning.
/// But you also tell dart that it never be null. see: `_user.value!`.
String? get user => _user.value!.email;

/// That line above will convert to this.
String? get user => null!.email;

您通过在下一个操作数之前添加 !null 标记为 not-null。这就是你得到错误的原因。要解决此问题,请使用 ? 而不是 !

/// This will return `null` and ignore the next `.email` operand
/// if `_user.value` is `null`.
String? get user => _user.value?.email;