因此,登录时一切顺利,但注销时抛出 _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/