Home > Mobile >  How to navigate to home screen after successfully login in flutter?
How to navigate to home screen after successfully login in flutter?

Time:02-01

Image

I'm using the following code for login. But the problem is after successfully login it's not able to navigate to home page. If I navigate inside on pressed button then it automatically navigate to home and it will not check either user exists or not.

try {
  final credential = await FirebaseAuth.instance.signInWithEmailAndPassword(
    email: emailAddress,
    password: password
  );
} on FirebaseAuthException catch (e) {
  if (e.code == 'user-not-found') {
    print('No user found for that email.');
  } else if (e.code == 'wrong-password') {
    print('Wrong password provided for that user.');
  }
}

I have called isUserLoggedIn function after pressing login button.

CodePudding user response:

Change like this,

try {
  final credential = await FirebaseAuth.instance.signInWithEmailAndPassword(
    email: emailAddress,
    password: password
  );
  //---------------------- add this part --------------
 if (user != null) {
   Navigator.of(context).pushNamedAndRemoveUntil(
                    '/home', (Route<dynamic> route) => false);
  // route set to use this. 
}
} on FirebaseAuthException catch (e) {
  if (e.code == 'user-not-found') {
    print('No user found for that email.');
  } else if (e.code == 'wrong-password') {
    print('Wrong password provided for that user.');
  }
}

You can also use this method,

Navigator.push(
    context, 
    MaterialPageRoute(
      builder: (context) => HomePage(),
    ),
  );

But If you use this, the user can back to login screen without signout. So, use pushNamedAndRemoveUntil method to navigate. It will remove all past routes. can't go back.

Read about pushNamedAndRemoveUntil

CodePudding user response:

If you just want to check for the user and navigate based on that, HoRiz has answered.

But I would suggest that you implement a state management solution first like BLoC, Riverpod, etc. It will help you to manage all your data like user info or any other data.

Also if you are not using named routes, then you can use this instead to navigate:

Navigator.pushReplacement(
                context,
                MaterialPageRoute(
                  builder: (context) => NewScreen(),
                ),
              );

Also, if want to learn all the things about routing then you can check Flutter's Oficial Website: Link

CodePudding user response:

Navigator.pushReplacement(context,MaterialPageRoute(builder: (context)=>HomePage()));

  • Related