简体   繁体   中英

How to make sure user is logged in using Firebase and Flutter

I want to check if the user is logged in then go to home page, if it is not logged in then go to login page.

The problem I am facing is, after I signed up, if I refresh it directly goes to home page even without logging in. I guess this is because after signing up (createUserWithEmailAndPassword) there is a current user. And I am checking that as the if condition.

Below shown is my code. Can anyone please help me? I want my user to go to home page only after logging in, not after signing up.

doo(context) async {
FirebaseUser user = await FirebaseAuth.instance.currentUser();
if (user == null) {
  Navigator.push(
    context,
    MaterialPageRoute(
      builder: (context) => LoginPage(),
    ),
  );
} else {
  Navigator.push(
    context,
    MaterialPageRoute(
      builder: (context) => MyHomePage(),
    ),
  );
 }
}

One way you can try to do this is by signing-out the user immediately after the sign-up, something like this..

FirebaseUser user;
    
user = await FirebaseAuth.instance.createUserWithEmailAndPassword(
  email: emailController.text,
  password: passwordController.text,
);

await FirebaseAuth.instance.signOut();


//then proceed with the logic for navigating to either LoginPage() or HomePage()
//..

You can check SharedPreferences. You can set value string in SharedPreferences and when user is login and in conditions check

if (user == null && sharedPrefs.getString('isLogin') != '')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM