Search code examples
flutternavigationflutter-go-router

Flutter: How to change page transition based on previous page


I have a Flutter web app with a custom side navigation bar which is displayed on every page. So that I can always show the same side navigation bar while still keeping URL navigation I am using the go_router package with all of the pages in a ShellRoute. Now I want to slide transition up to a navigation item below the current one and visa-verse. How can I achieve this?

Here's an over simplified version of my code

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp.router(
      routerConfig: GoRouter(
        initialLocation: "/dash",
        routes: [
          ShellRoute(
            builder: (context, state, child) => SideNavBarPage(subPage: child),
            routes: [
              GoRoute(
                path: '/dash',
                builder: (context, state) => DashPage(),
              ),
              GoRoute(
                path: '/other',
                builder: (context, state) => OtherPage(),
              ),
              GoRoute(
                path: '/another',
                builder: (context, state) => AnotherPage(),
              ),
            ],
          ),
        ],
      ),
    );
  }
}


class SideNavBarPage extends StatelessWidget {
  final Widget subPage;

  const SideNavBarPage({
    required this.subPage,
    super.key,
  });

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Row(
        children: [
          CustomSideNavBar(
            items: [
              CustomSideNavBarItem(onTap: () => context.go("/dash")),
              CustomSideNavBarItem(onTap: () => context.go("/other")),
              CustomSideNavBarItem(onTap: () => context.go("/another")),
            ],
          ),
          Expanded(child: subPage),
        ],
      ),
    );
  }
}

For example: if I wanted to switch from /another to /dash I would want to transition down from top to bottom, whereas from /dash to /other I would want to slide up from bottom to top.


Solution

  • Use go_router's StatefulShellRoute (see an example here).