Syed Ali Raza
Syed Ali Raza

Reputation: 161

How to properly implement logout functionality in flutter app?

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

Upvotes: 4

Views: 8205

Answers (1)

MichaelM
MichaelM

Reputation: 5818

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

Upvotes: 12

Related Questions