Search code examples
androidiosflutterdartflutter-go-router

How to apply transition animation to the .go function using the go_router package


I am using the go_router package because I need the deep linking it provides. I applied animation transitions to some routes but they are static, so every time I go to that route, the same animation is going to trigger. I would like to change the animation when I do GoRouter.of(context).go('/inbox')

This is what I have right now:

final router = GoRouter(
  initialLocation: '/inbox',
  routes: <GoRoute>[
    GoRoute(
      path: '/inbox',
      pageBuilder: (BuildContext context, GoRouterState state) {
        return PageTransition.slideFromRight(
          myChildWidget: Layout(
            context: context,
            state: state,
            child: EmailPage(),
          ),
          state: state,
        );
      },
    ),
    GoRoute(
      path: '/email/inbox/:id',
      pageBuilder: (BuildContext context, GoRouterState state) {
        return PageTransition.slideFromLeft(
          myChildWidget: Layout(
            context: context,
            state: state,
            child: const EmailDetailsPage(),
          ),
          state: state,
        );
      },
    ),
    GoRoute(
      path: '/menu',
      pageBuilder: (BuildContext context, GoRouterState state) {
        return PageTransition.slideFromRight(
          myChildWidget: Layout(
            context: context,
            state: state,
            child: const MenuPage(),
          ),
          state: state,
        );
      },
    )
  ],
);

PageTransition is just a custom transition Widget I build.

So, in this case, if I do GoRouter.of(context).go('/inbox') it will play the slideFromRight transition, if I do GoRouter.of(context).go('/email/inbox/:id') it will play the slideFromLeft and I can't change that. I would like for this to be dynamic and choose what animation it is going to play.


Solution

  • go_router provides CustomTransitionPage for transition animations.

    Code:

    GoRoute(
      path: 'details',
      pageBuilder: (context, state) {
        return CustomTransitionPage(
          key: state.pageKey,
          child: DetailsScreen(),
          transitionsBuilder: (context, animation, secondaryAnimation, child) {
            // Change the opacity of the screen using a Curve based on the the animation's
            // value
            return FadeTransition(
              opacity:
                  CurveTween(curve: Curves.easeInOutCirc).animate(animation),
              child: child,
            );
          },
        );
      },
    ),
    

    Reference: https://github.com/flutter/packages/blob/main/packages/go_router/example/lib/transition_animations.dart