Skip to content
Tutorials Center
My learning

Topics

Lesson 42 of 73 ยท Animation and graphics

Hero and Page Transitions

Learn Flutter Hero animations and custom page transitions: shared elements between routes, PageRouteBuilder, transition builders and the animations package.

When you tap a photo in a list and it seems to fly into the detail page, you are watching a Hero animation. The same image exists on two screens, and Flutter moves it from one place to the other while the routes change. This small trick tells the user "this is the same thing" better than any label could.

Hero animations are one half of this lesson. The other half is the transition of the page itself: the slide, fade or scale that plays when a route enters or leaves. You will learn how to replace the default with your own, and where the animations package fits. It builds on Navigator and Routes and on Explicit animations.

Real vs stand-in. The Dart code is real Flutter and read-only here. The live examples are JavaScript stand-ins: one computes the flight of a hero between two rectangles, the other shows how a route animation value (0 to 1) drives a transition. The real engine does this per frame on the GPU.

Two kinds of motion

Hero One widget flies between two screens.
Page transition The whole route slides, fades or scales.
1 / 2

A first Hero

Wrap the widget on both screens in a Hero with the same tag. The tag can be any object with a sensible ==: a string, an id, a record.

DART
class ProductTile extends StatelessWidget {
  const ProductTile({super.key, required this.product});
  final Product product;

  @override
  Widget build(BuildContext context) {
    return ListTile(
      leading: Hero(
        tag: 'product-image-${product.id}',
        child: Image.asset(product.image, width: 56, height: 56, fit: BoxFit.cover),
      ),
      title: Text(product.name),
      onTap: () => Navigator.of(context).push(
        MaterialPageRoute<void>(builder: (_) => ProductPage(product: product)),
      ),
    );
  }
}

class ProductPage extends StatelessWidget {
  const ProductPage({super.key, required this.product});
  final Product product;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text(product.name)),
      body: Column(
        children: [
          Hero(
            tag: 'product-image-${product.id}',      // same tag
            child: Image.asset(product.image, width: double.infinity, height: 280, fit: BoxFit.cover),
          ),
          // ...description, price...
        ],
      ),
    );
  }
}

Nothing else is required. The Navigator knows about heroes: when a push or pop starts, a HeroController (installed by MaterialApp) looks at the old and new route, finds heroes with matching tags, measures their rectangles, and then flies a copy of the widget through the overlay (a layer above all routes) between the two rectangles. When the flight ends, the destination hero appears at its place.

The tag must be unique per screen

Two heroes with the same tag on one screen cause an error, because Flutter cannot tell which one to fly. In a list, put the item id in the tag, like 'product-image-${product.id}', never a constant such as 'image'.

How the flight works

The flight is a tween between two Rects, driven by the route's animation and a curve. By default the rectangle tween is a straight line from the old rect to the new one (MaterialRectArcTween gives the curved arc you may know from Material). Think of it as interpolating left, top, width and height.

JS Stand-in: the flight of a hero

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Look at t=0.50: with an ease-in-out curve the hero is exactly halfway at the halfway point, and slower near the ends. On a back gesture the animation simply runs backwards, so the hero flies home. If the user drags the iOS back gesture halfway and lets go, the hero can even stop mid-air and return: that is why heroes are driven by the route's animation instead of a fixed timer.

Customizing a Hero

Hero has a few useful parameters:

  • createRectTween: replace the straight path, for example with MaterialRectArcTween(begin: a, end: b).
  • flightShuttleBuilder: build a different widget during the flight, for instance one that cross-fades from a thumbnail to a full image or keeps text from being squashed.
  • placeholderBuilder: what stays in the old position while the hero is away (by default an empty box of the same size).
  • transitionOnUserGestures: also animate when the user drags back with a gesture (off by default).
DART
Hero(
  tag: 'avatar-$userId',
  createRectTween: (begin, end) => MaterialRectArcTween(begin: begin, end: end),
  flightShuttleBuilder: (context, animation, direction, fromContext, toContext) {
    return ScaleTransition(scale: animation.drive(Tween(begin: 0.8, end: 1.0)), child: toContext.widget);
  },
  child: CircleAvatar(backgroundImage: AssetImage(path)),
)

Text inside a Hero can look odd mid-flight because its theme (font size, style) changes between screens. Wrap it in Material(type: MaterialType.transparency, child: Text(...)) so the text keeps its style while in the overlay.

Page transitions

MaterialPageRoute picks the transition from the platform and the theme. To control it yourself, use PageRouteBuilder, which gives your builder two animations: animation for this route entering, and secondaryAnimation for another route covering it.

DART
Route<void> fadeThrough(Widget page) {
  return PageRouteBuilder<void>(
    transitionDuration: const Duration(milliseconds: 350),
    reverseTransitionDuration: const Duration(milliseconds: 250),
    pageBuilder: (context, animation, secondaryAnimation) => page,
    transitionsBuilder: (context, animation, secondaryAnimation, child) {
      final curved = CurvedAnimation(parent: animation, curve: Curves.easeOutCubic);
      return FadeTransition(
        opacity: curved,
        child: SlideTransition(
          position: Tween<Offset>(begin: const Offset(0, 0.06), end: Offset.zero).animate(curved),
          child: child,
        ),
      );
    },
  );
}

// Navigator.of(context).push(fadeThrough(const SettingsPage()));

pageBuilder builds the screen once; transitionsBuilder is called on every frame with the animation value and wraps the screen in transition widgets such as FadeTransition, SlideTransition, ScaleTransition or RotationTransition. The page is not rebuilt each frame, which is why child is passed through.

Transitions for the whole app

To change every page at once, set the theme instead of building routes by hand:

DART
MaterialApp(
  theme: ThemeData(
    pageTransitionsTheme: const PageTransitionsTheme(builders: {
      TargetPlatform.android: ZoomPageTransitionsBuilder(),
      TargetPlatform.iOS: CupertinoPageTransitionsBuilder(),
    }),
  ),
)

With go_router (Declarative routing) you give each GoRoute a pageBuilder that returns a CustomTransitionPage, using the same transitionsBuilder shape.

JS Stand-in: one animation value, many transitions

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Every built-in transition widget is just this: a function from the animation value to a visual property. That is why you can combine them by nesting.

The animations package

The first-party animations package (add it to pubspec.yaml) implements Material motion patterns that are tedious to build by hand:

  • OpenContainer: a card or button that expands into a full page and shrinks back, a container transform.
  • PageTransitionSwitcher with SharedAxisTransition or FadeThroughTransition: for steps of a flow or for switching tabs.
  • SharedAxisPageTransitionsBuilder and FadeThroughPageTransitionsBuilder, usable in pageTransitionsTheme.
DART
OpenContainer<void>(
  closedBuilder: (context, open) => ListTile(title: const Text('Invoice 42'), onTap: open),
  openBuilder: (context, close) => InvoicePage(onBack: close),
  transitionDuration: const Duration(milliseconds: 400),
)

Choose the pattern by the relationship between the screens: a container transform when an item becomes its detail page, shared axis when moving through siblings (steps, tabs), fade through when the two screens are unrelated.

Radial hero, rotate routes and physics

A radial Hero

A normal Hero grows a rectangle into another rectangle along a straight line. A radial Hero, common for avatars and photo thumbnails, starts as a circle and ends as a rectangle, and flies along a curve. Two customizations produce it: a createRectTween that moves the bounds along an arc, and a flightShuttleBuilder (or the child itself) that morphs the clip radius from "fully round" to "square".

DART
Hero(
  tag: 'photo-${photo.id}',
  createRectTween: (begin, end) => MaterialRectCenterArcTween(begin: begin, end: end),
  child: ClipRRect(
    borderRadius: BorderRadius.circular(999),       // a circle at rest
    child: Image.asset(photo.path, fit: BoxFit.cover),
  ),
)

MaterialRectCenterArcTween moves the center of the rectangle on an arc (and MaterialRectArcTween moves corners). To animate the corners from round to square during the flight, give the destination a flightShuttleBuilder that reads the flight animation and builds ClipRRect(borderRadius: BorderRadius.circular(lerpDouble(999, 0, animation.value)!)). The radius is the interpolated value, so the shape morphs as the picture travels.

A rotating route

Any PageRouteBuilder can use any transition widget. A route that spins into place uses RotationTransition (turns are full rotations, so 0.25 is a quarter turn) with a fade:

DART
Route<void> spinIn(Widget page) => PageRouteBuilder<void>(
  transitionDuration: const Duration(milliseconds: 500),
  pageBuilder: (_, __, ___) => page,
  transitionsBuilder: (_, animation, __, child) {
    final curved = CurvedAnimation(parent: animation, curve: Curves.easeOutBack);
    return FadeTransition(
      opacity: animation,
      child: RotationTransition(
        turns: Tween<double>(begin: -0.1, end: 0).animate(curved),
        child: ScaleTransition(scale: Tween<double>(begin: 0.8, end: 1).animate(curved), child: child),
      ),
    );
  },
);

Keep rotation small and short: big spins are tiring and can trigger motion sensitivity, so honor MediaQuery.disableAnimationsOf(context) by skipping the effect (accessibility).

Physics: springs

Curves describe motion by a fixed shape over a fixed time. A physics simulation instead models a real object: you give mass, stiffness and damping, and the motion takes as long as it takes. It feels natural after a fling or drop because it starts from the gesture's own velocity.

DART
final spring = SpringDescription(mass: 1, stiffness: 180, damping: 14);
// or: SpringDescription.withDampingRatio(mass: 1, stiffness: 180, ratio: 0.7)

void snapBack(double velocity) {
  final simulation = SpringSimulation(spring, _controller.value, 0.0, velocity);
  _controller.animateWith(simulation);      // controller must be unbounded or 0..1 matches
}

Release a dragged card and pass the drag velocity into SpringSimulation so it springs back from where it was, at the speed it had. The ratio matters: below 1 the spring overshoots and wobbles (underdamped), at 1 it settles fastest without overshoot (critically damped), above 1 it creeps (overdamped). Curves.elasticOut imitates the first case when you only have a duration.

JS A damped spring, frame by frame

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Common mistakes

  • Duplicate tags on one screen (use ids in the tag).
  • The destination has no matching Hero, so nothing flies. Check that both tags are equal, including types: 1 and '1' differ.
  • Heroes in nested Navigators: a Hero only flies within the same Navigator.
  • Heavy widgets as hero children: a hero is rebuilt in the overlay, so keep it light.
  • Animating the page from build: use transitionsBuilder; do not rebuild a whole screen per frame.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What must two Hero widgets share so Flutter flies one into the other?

    The HeroController pairs heroes on the outgoing and incoming routes by equal tags.
  2. 2. In a list of products, which tag is correct for each image?

    Tags must be unique on a screen. A constant tag would appear many times; a random one would not match on the next screen.
  3. 3. In PageRouteBuilder, what does transitionsBuilder receive each frame?

    You wrap the child in transition widgets driven by the animation. The page itself is not rebuilt per frame.
  4. 4. Which package gives you a container transform where a card expands into a page?

    OpenContainer from the animations package implements the Material container transform.

Summary

  • A Hero with an equal tag on two routes flies through the overlay when the Navigator pushes or pops.
  • The flight is a rectangle tween driven by the route animation, so it reverses on back.
  • Use unique tags, light children, and flightShuttleBuilder to customize the flight.
  • PageRouteBuilder and PageTransitionsTheme replace page transitions; transition widgets map the animation value to a visual property.
  • The animations package supplies container transform, shared axis and fade through.

Next: CustomPaint and Canvas