'Set default transition for go_router in Flutter

as the docs from go_router describe, it is easy to set pageBuilder-Transitions for single pages. However, I want to set the default PageTransition for all pages.

How do I set the default page transition with/for go_router in Flutter?

Single Page:


  // this is the proposed method to do it for single pages
  // how can i apply it to all pages without writing the same code?
  GoRoute(
      path: '/login',
      builder: (context, state) => const LoginScreen(),
      pageBuilder: (context, state) => CustomTransitionPage<void>(
        key: state.pageKey,
        child: const LoginScreen(),
        transitionsBuilder: (context, animation, secondaryAnimation, child) =>
            FadeTransition(opacity: animation, child: child),
      ),
    ),

Best regards



Solution 1:[1]

The go_router package does not support this at the moment, but to reduce code duplication, you can create a helper function that would apply the custom transition for your route, like:

CustomTransitionPage<T> buildPageWithDefaultTransition({
  required BuildContext context, 
  required GoRouterState state, 
  required Widget child,
}) {
  return CustomTransitionPage<T>(
    key: state.pageKey,
    child: child,
    transitionsBuilder: (context, animation, secondaryAnimation, child) => 
      FadeTransition(opacity: animation, child: child),
  );
}

<...>

GoRoute(
  path: '/login',
  builder: (context, state) => const LoginScreen(),
  pageBuilder: (context, state) => buildPageWithDefaultTransition<void>(
    context: context, 
    state: state, 
    child: LoginScreen(),
  ),
),

Solution 2:[2]

The more correct way is inheritance from CustomTransitionPage.

class WebPage extends CustomTransitionPage {
  WebPage({
    LocalKey key,
    ... // other properties taken from `MaterialPage`
    required Widget child
  }) : super(
         key: key,
         transitionBuilder: (...) {
           return FadeTransition(...);
         }
         child: child, // Here you may also wrap this child with some common designed widget
       );
}

Then

GoRoute(
  path: '/login',
  builder: (context, state) => const LoginScreen(),
  pageBuilder: (context, state) => WebPage(
    key: state.pageKey,
    child: const LoginScreen(),
  ),
),

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mkobuolys
Solution 2 BambinoUA