Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 334
Marwin Lebensky Avatar asked Sep 13 '25 15:09

Marwin Lebensky


2 Answers

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 buildPageWithDefaultTransition<T>({
  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',
  pageBuilder: (context, state) => buildPageWithDefaultTransition<void>(
    context: context, 
    state: state, 
    child: LoginScreen(),
  ),
),
like image 189
mkobuolys Avatar answered Sep 15 '25 04:09

mkobuolys


This may be newer than these answers but the transition can be done in the theme rather than in the router code.

https://api.flutter.dev/flutter/material/PageTransitionsTheme-class.html

From that page:

   Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(
        useMaterial3: true,
        // Defines the page transition animations used by MaterialPageRoute
        // for different target platforms.
        // Non-specified target platforms will default to
        // ZoomPageTransitionsBuilder().
        pageTransitionsTheme: const PageTransitionsTheme(
          builders: <TargetPlatform, PageTransitionsBuilder>{
            TargetPlatform.iOS: CupertinoPageTransitionsBuilder(),
            TargetPlatform.linux: OpenUpwardsPageTransitionsBuilder(),
            TargetPlatform.macOS: FadeUpwardsPageTransitionsBuilder(),
          },
        ),
      ),
      home: const HomePage(),
    );
  }
like image 24
JOTN Avatar answered Sep 15 '25 06:09

JOTN