Using Firebase & Flutter, I store the displayName of a user on the auth Profile of firebase, as well as separately storing the first name and last name on the user doc.

When a user wants to change their first or last name I need to update the auth Profile displayName as well as the fields on the user's doc.

However, changing the profile with updateProfile returns a Future<void>, so I can't figure out how to conditionally await to determine whether to write to the user doc. For instance:

thisUser.updateProfile(displayName: displayName).then((val) {
  DatabaseService(uid: user.uid).updateUserData(
    firstName,
    lastName,
  );
  return;
}).catchError((e) {
  print(e.toString());
  return;
});

If a user has not recently authenticated, an error catches, which is all good, I initiate re-authenticating. However, in that case, I do not want to update the doc right away with the updateUserData function. However, in the above code, updateUserData is called regardless of success or error of updateProfile.

How can I call updateUserData ONLY if updateProfile is successful?


Solution 1: Tarik Huber

The Firebase Flutter auth SDK has a listener userChanges that you can use to update your doc:

FirebaseAuth.instance
  .userChanges()
  .listen((User user) {
    if (user == null) {
      print('User is currently signed out!');
    } else {
      // Update you doc here
      print('User is signed in!');
    }
  });

You can read more about it here. Basically it will trigger everytime something changes regarding the user. That way you don't need to await your updateProfile. This would be a general solution for your problem.