What is the right way to disable back button in flutter when one has reached the login page after logging out?

Viewed 131

I want to restrict the user from viewing inner pages of the app after the user has logged out and has been redirected to the login page. What I know so far is the use of Navigator.pop(context) or Navigator.of(context).pop() to move back to a previous page. But this isn't fitting in the use case I have mentioned (or maybe I don't know).

3 Answers

try pushAndRemoveUntil() instead of pop()

Navigator.of(context).pushAndRemoveUntil(MaterialPageRoute( builder: (ctx) => [Your login page]), (route) => false);
Navigator.of(context)
    .pushNamedAndRemoveUntil('/login', (Route<dynamic> route) => false);

this will clear all your stack behind after user will logout

I handle this by having an entirely separate widget tree depending on whether the user is logged in or not. Just below my ProviderContainer (riverpod), I have a widget that fetches the current user (as a stream so it's responsive). If it's null, I show the login/register tree. If it's not null, I show the normal home page. Any logout anywhere in the app immediately forces me via build back to the login tree. There's no "back" button at that point. They be gone.

Related