首页 > 解决方案 > 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

我怎么能做到这一点?

标签: firebasedartgoogle-cloud-firestorefirebase-authentication

解决方案


我想_firebaseAuth.authStateChanges()在我的方法 createUserInDatabaseIfNew 运行后被触发。

当用户的身份验证状态更改时,即他们的登录完成时,身份验证状态更改侦听器会触发。没有办法改变这种行为,也不应该有。

如果您想在用户在您的应用中注册完成时触发,您应该响应发出该信号的事件。所以如果注册意味着用户被写入数据库,你可以使用onSnapshot数据库上的监听器来检测用户注册。

您甚至可以将两者结合起来:

  1. 使用身份验证状态更改侦听器来检测登录何时完成。
  2. 在该身份验证状态侦听器中,然后为用户的注册文档附加一个快照侦听器。

推荐阅读