I want to implement logout functionality in my flutter app. There is a button in my side menu drawer logout and when the user presses the button I want the user to navigate to login screen and pop all other screens.
I have tried to do it and my code is
SharedPreferences prefs = await SharedPreferences.getInstance();
await prefs.remove('userPreference');
await Future.delayed(Duration(seconds: 2));
Navigator.of(context)
.popUntil(ModalRoute.withName(Navigator.defaultRouteName));
Navigator.of(context).pushReplacement(
MaterialPageRoute(
builder: (BuildContext context) =>
LoginScreen(),
)
);
Instead of using PushReplacement, use pushAndRemoveUntil. This pushes your new route, and removes routes routes from the navigation stack until the function passed in returns true. If you want to remove all other screens, then pass in a function that always returns false:
SharedPreferences prefs = await SharedPreferences.getInstance();
await prefs.remove('userPreference');
await Future.delayed(Duration(seconds: 2));
Navigator.of(context).pushAndRemoveUntil(
// the new route
MaterialPageRoute(
builder: (BuildContext context) => LoginScreen(),
),
// this function should return true when we're done removing routes
// but because we want to remove all other screens, we make it
// always return false
(Route route) => false,
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With