flutter: animate transition to named route

Issue

When I use Navigator.pushNamed(context, "/someRoute");, there is a minimal animation which slides in the new route from the bottom of the screen (on Android, might look different on iOS).

How can I add a custom animation to this transition?

I found this article, which has some very neat sample code for unnamed routes. They implement their own class which inherits from PageRouteBuilder and can be used like this: Navigator.push(context, SlideRightRoute(page: Screen2())). But a PageRouteBuilder is not a Widget and can’t be registered as a route in MaterialApp. So I don’t see how to apply this to named routes.

Solution

You need to use onGenerateRoute in your MaterialApp widget.

onGenerateRoute: (settings) {
  if (settings.name == "/someRoute") {
    return PageRouteBuilder(
      settings: settings, // Pass this to make popUntil(), pushNamedAndRemoveUntil(), works
      pageBuilder: (_, __, ___) => SomePage(),
      transitionsBuilder: (_, a, __, c) => FadeTransition(opacity: a, child: c)
    );
  }
  // Unknown route
  return MaterialPageRoute(builder: (_) => UnknownPage());
},

Answered By – CopsOnRoad

Answer Checked By – Clifford M. (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.