Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter Log Out & Replace Stack Beautifully

Tags:

flutter

At an arbitrary depth in my Flutter app, a user can log out of the app by tapping on a button. How can I replace the current stack of screens with the auth/login screen and have a "beautiful" animation for the transition?

I'm currently doing the following but the animation is not at all beautiful. On iOS, the screens on the stack slide out to the right and the auth screen slides in from the right. Too much sliding.

NavigatorState navigatorState = Navigator.of(this.context);
while (navigatorState.canPop()) {
  navigatorState.pop();
}

Navigator.pushReplacement(
  context,
  MaterialPageRoute(builder: (BuildContext context) {
    return AuthScreen();
  }),
);

I'd rather have the auth screen slide up from the bottom on iOS and have the auth screen appear with the normal animation on Android. Then have all the screens lower in the stack removed. I can't find a way to manipulate the stack this way in Flutter.

like image 618
Ted Henry Avatar asked Dec 11 '22 03:12

Ted Henry


2 Answers

try this out.

  Navigator.pushAndRemoveUntil(
      context,
      PageRouteBuilder(pageBuilder: (BuildContext context, Animation animation,
          Animation secondaryAnimation) {
        return AuthScreen();
      }, transitionsBuilder: (BuildContext context, Animation<double> animation,
          Animation<double> secondaryAnimation, Widget child) {
        return new SlideTransition(
          position: new Tween<Offset>(
            begin: const Offset(1.0, 0.0),
            end: Offset.zero,
          ).animate(animation),
          child: child,
        );
      }),
      (Route route) => false);

Here pushAndRemoveUntil will clear the stack and push new screen.

The PageRouteBuilder allows you to animate the screen transitions. You can play with it by returning FadeTransition or any which you prefer. This way you can achieve animated transition.

like image 181
Amol Gangadhare Avatar answered Jan 18 '23 12:01

Amol Gangadhare


If you declare routes in your MaterialApp like.

MaterialApp(
  home: new Screen1(),
  routes: <String, WidgetBuilder> {
    '/AuthScreen': (BuildContext context) => new AuthScreen()
  },
)

You can use

Navigator.of(context).pushNamedAndRemoveUntil('/AuthScreen', (Route<dynamic> route) => false);

Source of information

like image 41
Kalpesh Kundanani Avatar answered Jan 18 '23 13:01

Kalpesh Kundanani