【问题标题】:Null check operator used on a null value when logout using getX使用 getX 注销时对空值使用空值检查运算符
【发布时间】:2021-08-13 20:16:14
【问题描述】:

所以,登录时一切顺利,但注销时抛出了_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());
              },
            ),
          ),
        ],
      ),
    );
  }
}

我将不胜感激。

【问题讨论】:

  • 问题可以理解,请提供更多相关代码。

标签: flutter dart flutter-test flutter-getx


【解决方案1】:

这就是问题所在。

/// 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;

【讨论】:

  • 非常感谢,每当我编写代码时,这个空值检查让我感到困惑,颤振一直对我大喊要放置一个空值检查运算符,所以我只是在关注颤振错误修复。
  • 是的,一开始很困惑...请记住,当您想要一个可能是 null 的对象并且您还想访问其中的属性时,请使用 ? ...仅当您知道对象将永远存在并且永远不会是 null 时,才使用 !。如果你知道什么时候使用它们,你会没事的。空安全很酷! :)
猜你喜欢
  • 2021-08-11
  • 2021-08-10
  • 2021-06-15
  • 2021-08-04
  • 2021-11-10
  • 1970-01-01
  • 2021-11-11
  • 2021-09-25
  • 2021-12-03
相关资源
最近更新 更多