Sub topic 13
Custom pages and transitions
This chapter shows how to replace the animation go_router plays when a route appears or disappears. It assumes you can already define a GoRoute, call context.go and context.push, and read a basic ThemeData. It also assumes you know what an Animation<double> is.
Where pages come from
Every route in gorouter produces a Page. A Page is a description that the underlying Navigator turns into a real route with an animation. When you write builder:, gorouter wraps your widget in a default page: MaterialPage on Android and most platforms, and CupertinoPage when the app uses CupertinoApp.router. The page's transition is chosen by the platform.
When you write pageBuilder: instead, you return the Page yourself. That is the only hook for changing the transition of one route. Provide one of builder or pageBuilder on a route.
Building a CustomTransitionPage
CustomTransitionPage<T> is the general-purpose option. It takes a child (the screen), a transitionsBuilder, and optional durations. The transitionsBuilder receives four arguments:
context: the build context of the transition.animation: runs from 0 to 1 as this page enters and from 1 to 0 as it leaves.secondaryAnimation: runs from 0 to 1 when another page is pushed on top of this one.child: the screen widget you wrap.
The default transitionDuration and reverseTransitionDuration are both 300 milliseconds. You can set them separately, which is useful when you want a slow entrance and a quick exit.
The following program defines two reusable page helpers and uses them, along with NoTransitionPage, on a small router.
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
CustomTransitionPage<void> fadePage(GoRouterState state, Widget child) {
return CustomTransitionPage<void>(
key: state.pageKey,
child: child,
transitionsBuilder: (context, animation, secondaryAnimation, child) {
return FadeTransition(opacity: animation, child: child);
},
);
}
CustomTransitionPage<void> slideUpPage(GoRouterState state, Widget child) {
final Tween<Offset> offset = Tween<Offset>(
begin: const Offset(0, 1),
end: Offset.zero,
);
return CustomTransitionPage<void>(
key: state.pageKey,
child: child,
transitionDuration: const Duration(milliseconds: 350),
reverseTransitionDuration: const Duration(milliseconds: 250),
transitionsBuilder: (context, animation, secondaryAnimation, child) {
return SlideTransition(
position: animation.drive(
offset.chain(CurveTween(curve: Curves.easeOutCubic)),
),
child: child,
);
},
);
}
final GoRouter router = GoRouter(
routes: <RouteBase>[
GoRoute(
path: '/',
builder: (context, state) => const DemoScreen(title: 'Home'),
routes: <RouteBase>[
GoRoute(
path: 'fade',
pageBuilder: (context, state) =>
fadePage(state, const DemoScreen(title: 'Fade')),
),
GoRoute(
path: 'slide',
pageBuilder: (context, state) =>
slideUpPage(state, const DemoScreen(title: 'Slide up')),
),
GoRoute(
path: 'instant',
pageBuilder: (context, state) => NoTransitionPage<void>(
key: state.pageKey,
child: const DemoScreen(title: 'Instant'),
),
),
],
),
],
);
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp.router(routerConfig: router);
}
}
class DemoScreen extends StatelessWidget {
const DemoScreen({super.key, required this.title});
final String title;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text(title)),
body: Center(
child: Wrap(
spacing: 8,
children: [
ElevatedButton(
onPressed: () => context.push('/fade'),
child: const Text('Fade'),
),
ElevatedButton(
onPressed: () => context.push('/slide'),
child: const Text('Slide up'),
),
ElevatedButton(
onPressed: () => context.push('/instant'),
child: const Text('Instant'),
),
],
),
),
);
}
}Three details in this code matter.
animation.drive(tween.chain(CurveTween(...)))applies a curve without creating aCurvedAnimation. ACurvedAnimationyou create insidetransitionsBuilderis never disposed by you, sodriveavoids that leak.- The slide uses the same
animationfor entering and leaving. When the page is popped the animation runs backward, so the slide reverses on its own. NoTransitionPageis a ready-made page whose transition returns the child unchanged. Use it for tab-like destinations where an animation would feel wrong.
Why the page key matters
Pass key: state.pageKey to every page you create. The Navigator uses the key to decide whether an incoming page is the same page as before or a new one. If you omit the key, or reuse one key for different locations, the Navigator may update the existing page in place instead of animating a new one.
state.pageKey is derived from the route declaration, not from the concrete URL. Going from /books/1 to /books/2 therefore reuses the same page, and the screen rebuilds without a transition. If you want a transition between two parameter values of one route, build a key from the full location.
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
final GoRoute bookRoute = GoRoute(
path: '/books/:id',
pageBuilder: (context, state) {
return CustomTransitionPage<void>(
key: ValueKey<String>(state.uri.toString()),
child: Scaffold(
appBar: AppBar(title: Text('Book ${state.pathParameters['id']}')),
),
transitionsBuilder: (context, animation, secondaryAnimation, child) {
return FadeTransition(opacity: animation, child: child);
},
);
},
);Here /books/1 and /books/2 get different keys, so each location is a separate page and the fade plays between them.
Choosing a page type
| Page class | Transition | Use it when |
|---|---|---|
| `MaterialPage` | Platform default from the theme | You want the standard look and want to set `fullscreenDialog` or `maintainState` |
| `CupertinoPage` | iOS slide with swipe-back | The route must behave like iOS regardless of platform |
| `CustomTransitionPage` | Whatever `transitionsBuilder` returns | One route needs its own animation |
| `NoTransitionPage` | None | Instant switches, such as top-level destinations |
MaterialPage and CupertinoPage come from Flutter, not go_router. You can return them from pageBuilder to keep the default animation while still setting page options.
Changing the transition for the whole app
Writing a pageBuilder for every route is tedious if you only want a different default. Routes that use builder get a MaterialPage, and MaterialPage reads ThemeData.pageTransitionsTheme. Setting it once changes every such route.
import 'package:flutter/material.dart';
final ThemeData appTheme = ThemeData(
pageTransitionsTheme: const PageTransitionsTheme(
builders: <TargetPlatform, PageTransitionsBuilder>{
TargetPlatform.android: ZoomPageTransitionsBuilder(),
TargetPlatform.iOS: CupertinoPageTransitionsBuilder(),
},
),
);Pass appTheme to MaterialApp.router(theme: appTheme, ...). Use the theme for app-wide policy and pageBuilder for exceptions. Routes that return a CustomTransitionPage ignore the theme, because they supply their own animation.
Dialogs and full-screen modals
CustomTransitionPage also accepts opaque, barrierColor, barrierDismissible, barrierLabel and fullscreenDialog. Setting opaque: false with a semi-transparent barrierColor lets the previous page show through, which gives you a route-based dialog or bottom sheet. Navigate to it with context.push so the page below stays in the stack.
Common errors
- No animation appears. The route probably uses
context.gointo a page with an unchanged key, or you gave every page the same hard-coded key. Usestate.pageKeyor a location-based key. - The page appears for a frame, then jumps. A
transitionsBuilderthat ignoreschildshows nothing real. Always includechildin the widget you return. - The old page does not react when a new one covers it. Custom transitions do nothing with
secondaryAnimationunless you use it. If you want the outgoing page to slide away, wrap its content in a second transition driven bysecondaryAnimation. - The back swipe on iOS stops working. A
CustomTransitionPagedoes not provide the Cupertino swipe-back gesture. If you need it, useCupertinoPagefor that route. - Type mismatch on result. If you await
context.push<bool>(...), create the page asCustomTransitionPage<bool>so the result type matches.
Exercises
Exercise
A route /books/:id uses a CustomTransitionPage with key: state.pageKey. You call context.go('/books/2') while /books/1 is showing, and no transition plays. Why, and how do you fix it?
Show answer
state.pageKey comes from the route declaration, so both locations share one key and the Navigator updates the existing page instead of adding a new one. Use a key built from the full location, for example ValueKey<String>(state.uri.toString()), so each URL is a separate page.
Exercise
You want every route built with builder: to use ZoomPageTransitionsBuilder on Android, but only /settings should have no animation. Which two mechanisms do you combine?
Show answer
Set ThemeData.pageTransitionsTheme with ZoomPageTransitionsBuilder for TargetPlatform.android to change the default for all builder routes. Then give the /settings route a pageBuilder that returns NoTransitionPage with key: state.pageKey.
Exercise
Why is animation.drive(Tween(...).chain(CurveTween(...))) preferred over creating a CurvedAnimation inside transitionsBuilder?
Show answer
transitionsBuilder runs on every build, and a CurvedAnimation created there is never disposed by your code. drive returns a derived animation without that leak.