flutterflutter-go-routergorouterpage-transition

Flutter: GoRouter slide transition direction


I make GoRouter work with slide transitions. I want the transition to slide from right to left when the router makes push and left to right when the router pops.

Here is the working code:

transition_factory.dart

static CustomTransitionPage getSlideTransitionPage(
  {required BuildContext context,
  required GoRouterState state,
  required Widget child,
  required bool leftToRight}) {
return CustomTransitionPage(
  key: state.pageKey,
  child: child,
  transitionsBuilder: (context, animation, secondaryAnimation, child) =>
      SlideTransition(
          position: animation.drive(
            Tween<Offset>(
              begin: Offset(0.75, 0),
              end: Offset.zero,
            ).chain(CurveTween(curve: Curves.easeIn)),
          ),
         // textDirection:
          //    leftToRight ? TextDirection.ltr : TextDirection.rtl,
          child: child),
);

}
static Page<dynamic> Function (BuildContext context, GoRouterState state) getSlidePageBuilder(
  {
  required Widget child,
  required bool leftToRight}) {
return (context, state) => TransitionFactory.getSlideTransitionPage(
    context: context, state: state, child: child, /*leftToRight: leftToRight*/);
}

router.dart

GoRoute(
    path: "/",
    pageBuilder: TransitionFactory.getSlidePageBuilder(
        child: const Home(), /*leftToRight: !Router.goingBack*/),

GoRoute(
    path: "/menu",
    //builder: (context, state) => const Menu(),
    pageBuilder: TransitionFactory.getSlidePageBuilder(
        child: const Menu(), /*leftToRight: !Router.goingBack*/),
  

First, I tried to change the transition direction myself by changing the TextDirection property, but then, at some point, I realized that code works as needed by default.

When going from Home to Menu i.e. push the transition is right to left. When going back from Menu to Home using pop the transition is left to right.

This is exactly what I want but I don't understand Why? What makes it work like this? I cannot see something about this in any documentation.


Solution

  • Here's a breakdown of how it works:

    Pushing a new route: Animation value goes from 0 to 1. SlideTransition's position property is driven by a Tween that goes from Offset(0.75, 0) to Offset.zero. As a result, the transition appears to slide from right to left.

    Popping a route: Animation value goes from 1 to 0. The Tween now drives the SlideTransition's position property from Offset.zero back to Offset(0.75, 0). As a result, the transition appears to slide from left to right.