Flutter: Changing page transition in Navigator 2.0

Viewed 1628

I have a Router that works likes this: In the first step there is a MaterialPage being created:

return MaterialPage(
      child: SomePage(),
      key: keyName,
      name: pageName,
      arguments: routeSettings.arguments,
    );

and added to the array of Pages then notifyListeners() is called. This router class has a build method like this:

return Navigator(
      key: navigatorKey,
      pages: List.of(_pages),
      onPopPage: _onPopPage,
    );

Now my question is where can change page transition for some pages in such a setting? I was trying to use page_transition package but it returns a PageTransition object not a Widget which is required in MaterialPage.

1 Answers

You can use a PageRouteBuilder to implement different page transitions. For example a slide animation:

class SlideRoute extends PageRouteBuilder {
  final Widget page;
  final RouteSettings settings;
  SlideRoute({required this.page, required this.settings})
      : super(
          pageBuilder: (
            BuildContext context,
            Animation<double> animation,
            Animation<double> secondaryAnimation,
          ) =>
              page,
          settings: settings,
          transitionsBuilder: (
            BuildContext context,
            Animation<double> animation,
            Animation<double> secondaryAnimation,
            Widget child,
          ) =>
              SlideTransition(
            position: Tween<Offset>(
              begin: const Offset(1, 0),
              end: Offset.zero,
            ).animate(animation),
            child: child,
          ),
        );
}

Then you can use this when returning a route, for example with onGenerateRoute of MaterialApp:

MaterialApp(
  onGenerateRoute: (settings) {
    switch (settings.name) {
      case '/route1':
        return SlideRoute(page: Route1(), settings: settings);
      case '/route2':
        return SlideRoute(page: Route2(), settings: settings);
    }
  },
)
Related