flutterdartanimation

Flutter: Disable push transition animation but enable it for pop


In Flutter, how do I push a page without any transition animation but when I pop it, I'd like the page to slide from top to bottom.

The following code works partially. It disables the animation during push, but it also disables the animation during pop.

// Push without animation
Navigator.push(
  context,
  PageRouteBuilder(
    pageBuilder: (context, animation, secondaryAnimation) => MyNewPage(),
    transitionDuration: Duration.zero, // No animation when pushing
  ),
);

// Pop with the default animation (does not work)
Navigator.pop(context);

Solution

  • This happens because you are creating a PageRouteBuilder without a transition, so transitionDuration does not yet have any impact.

    Try the following PageRouteBuilder with a slide transition:

    PageRouteBuilder(
      pageBuilder: (context, animation, secondaryAnimation) => const MyNewPage(),
      transitionDuration: Duration.zero,
      // reverseTransitionDuration: Duration.zero,
      transitionsBuilder: (context, animation, secondaryAnimation, child) {
        const begin = Offset(0.0, 1.0);
        const end = Offset.zero;
        const curve = Curves.ease;
    
        var tween = Tween(begin: begin, end: end).chain(
          CurveTween(curve: curve)
        );
        
        return SlideTransition(
          position: animation.drive(tween),
          child: child,
        );
      },
    );
    

    Now, you should be able to use transitionDuration to achieve the desired effect. reverseTransitionDuration can be used if you want to do the opposite (no transition during pop).

    For completeness, if you actually want different transitions for push and pop, you can use animation.status and conditionally return a different transition whether the animation is forward or reverse.