flutter - 使用 getX 注销时对空值使用空检查运算符

标签 flutter dart flutter-test flutter-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();
});

这个来 self 的主屏幕

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;

关于flutter - 使用 getX 注销时对空值使用空检查运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67690464/

相关文章:

flutter - 如何使用列表和带有Flutter的颜色设置颜色?

string - Flutter如何生成随机字符串

listview - 将静态项目附加到从数据库数据生成的 ListView.builder

dart - Android Manifest com.apptreesoftware.barcodescan中 Unresolved Flutter软件包

Flutter 如何模拟对 rootBundle.loadString(...) 的调用,然后重置模拟的行为?

Flutter Listview Widget 测试失败并在列表中找不到错误文本?

flutter - 如果语句在我的 Dart Flutter 代码中被注册为变量?我该如何改变?

firebase - 发布应用程序 com.google.android.gms.common.api.b 10 后 Flutter Google Sign 和 Phone Auth 错误

android - 使用共享首选项保存列表时遇到问题(仍然需要帮助)

dart - 在 Dart 中,如果我不知道函数的类型,我是否使用 dynamic 或 Object 注释函数返回值?