Home > Back-end >  Firebase Authorization is not checking if the user is logged in properly
Firebase Authorization is not checking if the user is logged in properly

Time:03-04

in my flutter app I want to check if a user is logged in before or not and based on this navigate them to either HomePage or SignIn page. The code I am using is not working fine, it is not navigating to the SignIn page after I've done registration and deleted the account in Firebase Console. In short, when I delete a user, who registered well before, in Firebase Console the application is keeping to show the HomePage and all the posts the user made. How can I handle it?

"In short, I want to navigate the user to SignIn page after I delete his account in Firebase Console"

Here is the code in my main.dart file:

_check(){
 final FirebaseAuth auth = FirebaseAuth.instance;
 final User? user = auth.currentUser;
 if(user == null){
   HiveDB.deleteUser();
   return SignInPage();
 }
 HiveDB.putUser(id: user.uid);
 return HomePage();
}

@override
void initState() {
  // TODO: implement initState
  super.initState();
   _check();
}

@override
Widget build(BuildContext context) {
  return MaterialApp(
    home: _check(),
    routes: {
      SignInPage.id:(context) => SignInPage(),
      SignUpPage.id:(context) => SignUpPage(),
      HomePage.id:(context) => HomePage(),
    },
  );
}

The _check() function is not working as it's desired...

CodePudding user response:

This is something that can be resolved by using async . the problem is you are getting response in future but the action is performed before. Please check the following documentation for detailed overview: https://dart.dev/codelabs/async-await

CodePudding user response:

While Firebase persists the user info in local storage and automatically restores it when the app/page reloads, this requires that it makes an asynchronous call to the server and thus may not be ready by the time your check runs.

Instead of depending on currentUser, you'll want to listen for changes to the authentication state through the authStateChanges stream. Most apps wrap this in a StreamBuilder and then show the correct screen based on the stream state and last event.

  • Related