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
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(),
),
),
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(),
);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With