Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly implement logout functionality in flutter app?

Tags:

flutter

dart

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(),
     )
);
like image 748
Syed Ali Raza Bokhari Avatar asked Dec 17 '22 16:12

Syed Ali Raza Bokhari


1 Answers

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,
);
like image 145
MichaelM Avatar answered Dec 20 '22 04:12

MichaelM