Flutter bloc registration trouble

Viewed 57

I have bloc, which listen to changes of currentUser state from firebase.

 AuthBloc({@required AuthService authService})
  : assert(authService != null),
    _authService = authService,
    super(AuthInitial()) {
_userSubscription = _authService.currentUser
    .listen((user) => add(AuthenticationUserChanged(user)));
}

Then add event and the event call this function

Stream<AuthState> _mapAuthenticationUserChangedToState(
  AuthenticationUserChanged event) async* {
if (event.user != null) {

   // TO GET CUSTOM USER FROM FIRESTORE because of expiration, etc.
  var user = await _authService.getUser(event.user.uid);
  if (user.expiration == "") {
    yield NotAuthorized(user);
  } else {
    var isAfter =
        DateTime.now().toUtc().isAfter(DateTime.fromMillisecondsSinceEpoch(
              user.expiration.millisecondsSinceEpoch,
              isUtc: false,
            ).toUtc());

    if (isAfter) {
      yield NotAuthorized(user);
    } else {
      yield Authenticated(event.user);
    }
  }
} else {
  yield Unautheticated();
}

But in my RegisterCubit I have signUpSubmitted method, which creates Firebase user and immediately after this is called my AuthBloc, which make sense. But in my Bloc i need my custom Firestore user, which i have to create after FirebaseUser creation(because I need UID and email).

And this is the problem.

Future<void> signUpFormSubmitted() async {
if (!state.status.isValidated) return;
emit(state.copyWith(status: FormzStatus.submissionInProgress));
try {
  await _authService
      .registerUser(state.email.value, state.password.value)
      .then((value) async {
        // THIS IS CALLED AFTER BLOC
        // I NEED TO CALL IT AFTER _registerUser() but in front of BLOC
    var user =
        ApplicationUser(uid: value.user.uid, email: value.user.email);
    await _authService.addUserToDocument(user);
  });

  emit(state.copyWith(status: FormzStatus.submissionSuccess));
} on Exception {
  print(Exception);
  emit(state.copyWith(status: FormzStatus.submissionFailure));
}
}

My AuthService methods

Future<UserCredential> registerUser(email, password) =>
  _auth.createUserWithEmailAndPassword(email: email, password: password);

Future<void> addUserToDocument(ApplicationUser user) {
return _db.collection('users').doc(user.uid).set({
  'uid': user.uid,
  'firstname': '',
  'lastname': '',
  'age': '',
  'expiration': '',
  'email': user.email
});
}
  
0 Answers
Related