Payel Masanta
Payel Masanta

Reputation: 30

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(),
    ),
  );
 }
}

Upvotes: 0

Views: 71

Answers (2)

Jigar Patel
Jigar Patel

Reputation: 5423

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()
//..

Upvotes: 1

Captivity
Captivity

Reputation: 338

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') != '')

Upvotes: 0

Related Questions