flutternavigationflutter-go-routerauto-routeflutter-beamer

Go Router: How to implement nested navigation inside a widget


I want to add nested navigation inside a widget same as this gif: demo. I know this feature is available in packages like beamer and auto_route but I want to know if this is possible with go_router as well.


Solution

  • You can achieve this by using two Router.withConfig widgets from Flutter and passing two separate GoRouters to them, like so:

    import 'package:flutter/material.dart';
    import 'package:go_router/go_router.dart';
    
    void main() {
      runApp(
        MaterialApp(
          home: Scaffold(
            body: Body(),
          ),
        ),
      );
    }
    
    class Body extends StatefulWidget {
      const Body({super.key});
    
      @override
      State<Body> createState() => _BodyState();
    }
    
    class _BodyState extends State<Body> {
      final router1 = GoRouter(
        routes: [
          GoRoute(
            path: '/',
            builder: (context, state) => const Page(),
            routes: [
              GoRoute(
                path: 'sub-page',
                builder: (context, state) => const Page(),
              ),
            ],
          ),
        ],
      );
      final router2 = GoRouter(
        routes: [
          GoRoute(
            path: '/',
            builder: (context, state) => const Page(),
            routes: [
              GoRoute(
                path: 'sub-page',
                builder: (context, state) => const Page(),
              ),
            ],
          ),
        ],
      );
    
      @override
      Widget build(BuildContext context) {
        return Row(
          children: [
            Expanded(
              child: Padding(
                padding: const EdgeInsets.all(16),
                child: Router.withConfig(config: router1),
              ),
            ),
            Expanded(
              child: Padding(
                padding: const EdgeInsets.all(16),
                child: Router.withConfig(config: router2),
              ),
            ),
          ],
        );
      }
    }
    
    class Page extends StatelessWidget {
      const Page({super.key});
    
      @override
      Widget build(BuildContext context) {
        final route = ModalRoute.of(context)!.settings.name;
    
        return Scaffold(
          appBar: AppBar(
            title: const Text('Title'),
          ),
          body: InkWell(
            onTap: () => context.go('/sub-page'),
            child: Center(
              child: Text('Route: $route'),
            ),
          ),
        );
      }
    }
    

    enter image description here