Home > Enterprise >  Firebase Auth failing with null safety
Firebase Auth failing with null safety

Time:04-17

I have a Firebase Auth login function that I have had to change some code on to allow null safety

This particular section of the Auth function is proving tricky

Future<String> getCurrentUser() async {
    User? user = await _firebaseAuth.currentUser;
    return user!.uid;
  }

I have code without errors, until I run. Then it fails on the return statement with Null check operator used on a null value.

This is when there is no user logged in so there is no current user to return.

I have to install null safety but in doing so the null check is doing its job, seeing there is no current user and failing.

I am then able to press 'play' on the simulator and the code works fine on the sim, but in production this wouldn't work and needs fixing.

When I then press restart again without a user logged in it fails, and pressing 'play' seems to make it happy and it works fine despite just having a null returned.

Is there a way to solve this? I have tried an if but I still need to return user!.uid; at the end

Any help appreciated, thanks

CodePudding user response:

The ideal implementation for all apps is to use an authentication state observer using authStateChanges(). This will give you a callback any time the user is know to be fully signed in or signed out. This will let you adjust your UI based on that state. Implemented correctly, this will give you a way to immediately respond to the user's state, and will also give you the moment that a user object is first available if they were previously signed in and have just launched the app again.

FirebaseAuth.instance
  .authStateChanges()
  .listen((User? user) {
    if (user == null) {
      print('User is currently signed out!');
    } else {
      print('User is signed in!');
    }
  });

To be clear: do not use currentUser unless you just need a quick check of the user's sign in state. It's better to listen to the changes over time and respond to them as they occur.

CodePudding user response:

You could return an empty String if user is null.

Future<String> getCurrentUser() async {
    User? user = await _firebaseAuth.currentUser;
    if(user != null){
      return user!.uid;
    } else {
      return "";
    }
  }

Then when you call your method, you can check if the result is empty or not:

String userId = await getCurrentUser();
if(userId != ""){
  // Do stuff when user is logged in
} else{
  // Do stuff when user is not logged in
}
  • Related