firebase - Firebase Auth authStateChanges 触发器
问题描述
我正在使用 firebase 对用户进行身份验证并在 firestore 数据库中创建用户:
final auth.FirebaseAuth _firebaseAuth;
Future<void> signUp(
{@required String email, @required String password}) async {
assert(email != null && password != null);
try {
await _firebaseAuth.createUserWithEmailAndPassword(
email: email, password: password);
await createUserInDatabaseIfNew();
} on Exception {
throw SignUpFailure();
}
}
使用firebase,一旦.createUserWithEmailAndPassword()
执行该方法,它就会立即触发authStateChanges
,我在代码中使用该方法将新用户发送到user
流中,并最终从数据库中检索其数据
Stream<User> get user {
return _firebaseAuth.authStateChanges().map((firebaseUser) {
return firebaseUser == null ? User.empty : firebaseUser.toUser;
});
}
StreamSubscription<User> _userSubscription = _authenticationRepository.user.listen((user) {
return add(AuthenticationUserChanged(user));}
if(event is AuthenticationUserChanged){
if(event.user != User.empty){
yield AuthenticationState.fetchingUser();
User userFromDatabase;
try{
var documentSnapshot = await _firebaseUserRepository.getUser(event.user.id);
userFromDatabase = User.fromEntity(UserEntity.fromSnapshot(documentSnapshot));
yield AuthenticationState.authenticated(userFromDatabase);
}
我面临的问题是,由于_firebaseAuth.createUserWithEmailAndPassword
,在数据库中创建用户之前_firebaseAuth.authStateChanges
触发,最终当我尝试检索该用户时,它仍然不存在于数据库中。
我想在我的方法运行后被_firebaseAuth.authStateChanges()
触发。createUserInDatabaseIfNew
我怎么能做到这一点?
解决方案
我想
_firebaseAuth.authStateChanges()
在我的方法 createUserInDatabaseIfNew 运行后被触发。
当用户的身份验证状态更改时,即他们的登录完成时,身份验证状态更改侦听器会触发。没有办法改变这种行为,也不应该有。
如果您想在用户在您的应用中注册完成时触发,您应该响应发出该信号的事件。所以如果注册意味着用户被写入数据库,你可以使用onSnapshot
数据库上的监听器来检测用户注册。
您甚至可以将两者结合起来:
- 使用身份验证状态更改侦听器来检测登录何时完成。
- 在该身份验证状态侦听器中,然后为用户的注册文档附加一个快照侦听器。
推荐阅读
- python - 尝试通过 CMD 安装 CUDA 时出错
- ios - Visual Studio iOS 自动预配证书密码
- discord.py - 在 json 文件中存储前缀时如何在 Cog 中找到机器人的前缀
- flutter - “WidgetsBinding.instance!.addPostFrameCallback((_) => yourFunction(context));” 不执行
- sql - 处理日期数据类型中的零值
- excel - 使用 Sheets.Range.Formula 属性时开始一个新行
- r - 查找特定的小数点数字
- javascript - 异步迭代集合
- llvm - 什么时候应该对 LLVM IR 使用“volatile”?
- php - 无法摆脱 PHP 回显中的额外空间