Sub topic 8
Customizing page transitions
This chapter assumes you can push and pop routes with Navigator, know what MaterialPageRoute does, and are comfortable with basic animation widgets such as FadeTransition. You don't need to know AnimationController in depth. The Navigator creates and disposes the controller for you.
Where transitions come from
Every route on the Navigator stack owns an AnimationController. When you push a route, its animation runs from 0.0 to 1.0. When you pop it, the animation runs back from 1.0 to 0.0. The route's buildTransitions method wraps the page in widgets that read that animation, so the screen slides, fades, or zooms.
A route gets its transition from one of three places:
| Source | Scope | Use it when |
|---|---|---|
| `PageTransitionsTheme` | Every `MaterialPageRoute`, per platform | You want one consistent style across the app |
| `PageRouteBuilder` | One route | A single screen needs a special effect |
| `CustomTransitionPage` (go_router) | One `GoRoute` | You use go_router and need per-route control |
Two animations per transition
The transitionsBuilder callback receives two animations.
animationdrives the route being pushed or popped. It runs forward when the route enters and in reverse when it leaves.secondaryAnimationdrives the route that is already on the stack. It runs forward when another route is pushed on top of this one and in reverse when that route is popped.
So a route is both the "incoming" page and, later, the "covered" page. A well-designed transition handles both roles.
A custom route with PageRouteBuilder
PageRouteBuilder creates a route from two callbacks. pageBuilder returns the screen, and transitionsBuilder wraps it in animation widgets. The example below is a complete app. The detail screen slides up from the bottom and fades in, and the home screen slides slightly left while it is covered.
import 'package:flutter/material.dart';
void main() => runApp(const MaterialApp(home: HomeScreen()));
Route<T> slideUpRoute<T>(Widget page) {
return PageRouteBuilder<T>(
transitionDuration: const Duration(milliseconds: 350),
reverseTransitionDuration: const Duration(milliseconds: 200),
pageBuilder: (context, animation, secondaryAnimation) => page,
transitionsBuilder: (context, animation, secondaryAnimation, child) {
final slide = Tween<Offset>(
begin: const Offset(0, 1),
end: Offset.zero,
).chain(CurveTween(curve: Curves.easeOutCubic)).animate(animation);
final covered = Tween<Offset>(
begin: Offset.zero,
end: const Offset(-0.1, 0),
).animate(secondaryAnimation);
return SlideTransition(
position: covered,
child: SlideTransition(
position: slide,
child: FadeTransition(opacity: animation, child: child),
),
);
},
);
}
class HomeScreen extends StatelessWidget {
const HomeScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Home')),
body: Center(
child: ElevatedButton(
onPressed: () => Navigator.of(context)
.push(slideUpRoute<void>(const DetailScreen())),
child: const Text('Open details'),
),
),
);
}
}
class DetailScreen extends StatelessWidget {
const DetailScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Details')),
body: Center(
child: ElevatedButton(
onPressed: () => Navigator.of(context).pop(),
child: const Text('Go back'),
),
),
);
}
}A few details matter here:
Tween.chain(CurveTween(...))applies the curve first and then maps the result through the tween. You then call.animate(animation)to get anAnimation<Offset>. This avoids creating aCurvedAnimation, which you would otherwise have to dispose.reverseTransitionDurationlets the pop be faster than the push. Without it, both directions usetransitionDuration.- The
childargument is the page you returned frompageBuilder. The framework builds it once and reuses it on every animation frame. Don't rebuild the page insidetransitionsBuilder.
Route properties that affect the effect
PageRouteBuilder has other parameters that change how the transition looks.
opaquedefaults totrue. If your transition is partly transparent, as in a fade, the route below still isn't painted, because the Navigator skips it once the top route is fully opaque. Setopaque: falsefor overlays and sheets where the previous screen must stay visible.barrierColorandbarrierDismissibleadd a dimmed layer behind a non-opaque route. They default to no barrier.maintainStatekeeps the covered route's state alive. It defaults totrue. Setting it tofalsedisposes the route below when it's fully covered, which saves memory but loses scroll positions and form input.fullscreenDialogonMaterialPageRoutemakes the page slide up and swaps the back arrow for a close icon.
Choosing the curve
The curve you apply controls how the motion feels. Curves.easeOutCubic suits entering content, because it starts fast and settles. Curves.easeInCubic suits leaving content.
Be careful with curves that overshoot, such as Curves.elasticOut or Curves.easeOutBack. The value goes above 1.0 or below 0.0. SlideTransition copes with that, but FadeTransition throws an assertion error if opacity leaves the range 0.0 to 1.0. If you want a bounce on a slide and a fade on the same route, give each its own animation. Pass the plain animation to the fade, or clamp the curved value.
Setting transitions for the whole app
For a consistent style, don't build every route by hand. Set pageTransitionsTheme on ThemeData, and each MaterialPageRoute will use the builder for the current platform.
import 'package:flutter/material.dart';
void main() {
runApp(
MaterialApp(
theme: ThemeData(
pageTransitionsTheme: const PageTransitionsTheme(
builders: <TargetPlatform, PageTransitionsBuilder>{
TargetPlatform.android: ZoomPageTransitionsBuilder(),
TargetPlatform.iOS: CupertinoPageTransitionsBuilder(),
},
),
),
home: const Scaffold(body: Center(child: Text('Home'))),
),
);
}Flutter ships several builders:
ZoomPageTransitionsBuilderis the current Android style.FadeUpwardsPageTransitionsBuilderis an older Android style.OpenUpwardsPageTransitionsBuilderis another older Android style.CupertinoPageTransitionsBuilderis the iOS slide, and it supports the edge-swipe back gesture.
You can also write your own by extending PageTransitionsBuilder and overriding buildTransitions.
Two gotchas come up often:
- The theme only affects
MaterialPageRouteand routes created fromMaterialPage. APageRouteBuilderignores it. - A platform missing from
buildersfalls back to a default. If you list only Android, an iOS device still gets a fallback transition.
Transitions in go_router
With go_router, a GoRoute normally uses builder, and the router wraps your widget in a platform-appropriate page. To control the transition, use pageBuilder instead and return a CustomTransitionPage.
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
final GoRouter router = GoRouter(
routes: [
GoRoute(
path: '/',
builder: (context, state) => const HomeScreen(),
routes: [
GoRoute(
path: 'details',
pageBuilder: (context, state) => CustomTransitionPage<void>(
key: state.pageKey,
transitionDuration: const Duration(milliseconds: 300),
child: const DetailScreen(),
transitionsBuilder:
(context, animation, secondaryAnimation, child) {
return FadeTransition(opacity: animation, child: child);
},
),
),
GoRoute(
path: 'settings',
pageBuilder: (context, state) => NoTransitionPage<void>(
key: state.pageKey,
child: const SettingsScreen(),
),
),
],
),
],
);state.pageKey gives the page a stable identity. Without a key, the Navigator can treat two pages as the same entry and skip the transition. NoTransitionPage is useful for tab-like destinations, where a slide would imply a hierarchy that doesn't exist.
Common errors
- Nothing animates. You usually returned a page from
pageBuilderwithout wrapping it in a transition, or you usedNoTransitionPageby mistake. Check thattransitionsBuilderreturns a widget that readsanimation. - The transition runs but the back swipe on iOS is gone. A custom
PageRouteBuilderdoesn't provide the Cupertino edge-swipe gesture. If you need it, extendCupertinoPageRouteor useCupertinoPageTransitionsBuilderthrough the theme. - Assertion about opacity. An overshooting curve fed into
FadeTransition, as described above. - Jank on a heavy page. The animation rebuilds the transition wrappers each frame, and an expensive
pageBuildermakes it worse. Keep the pageconstwhere you can, and avoid work intransitionsBuilderbeyond building the transition widgets. - Hero animations stop working.
Heroflights run on the route'sanimation. If you setopaque: falseor use a zero-duration transition, the flight may look wrong or be skipped.
Exercise
You wrote a PageRouteBuilder whose transition fades the new page in with Curves.elasticOut, and you see an assertion error during the animation. What causes it, and how do you fix it?
Show answer
Curves.elasticOut overshoots, so the animation value goes above 1.0, and FadeTransition requires opacity between 0.0 and 1.0. Fix it by giving the fade the plain animation (or a curve that stays in range, or a clamped value), and apply the elastic curve only to a transition that tolerates overshoot, such as SlideTransition or ScaleTransition.
Exercise
Your app sets pageTransitionsTheme to use CupertinoPageTransitionsBuilder on every platform, but one screen opened with PageRouteBuilder still has a different animation. Why?
Show answer
PageTransitionsTheme only applies to MaterialPageRoute and MaterialPage. A PageRouteBuilder builds its own transition through its transitionsBuilder, so the theme is ignored. To get the theme's transition there, call the theme's builder from your transitionsBuilder, or use MaterialPageRoute for that screen.
Exercise
In go_router, how do you make the /settings route appear instantly with no animation, and why should you pass state.pageKey?
Show answer
Use pageBuilder and return NoTransitionPage<void>(key: state.pageKey, child: const SettingsScreen()). The key gives the page a stable identity, so the Navigator can tell it apart from other pages and update it correctly.