tezvyn:

Flutter Nested Navigation: Routers Within Routers

AI-drafted, machine-checkedSource: docs.flutter.devintermediate

Nested Navigation is like having a mini-app with its own back button inside a single screen. It's used for UIs like a BottomNavigationBar where each tab needs its own navigation history. The footgun is calling the wrong Navigator's context.

WHY IT EXISTS Some UI patterns require independent navigation flows within a single screen. Without nesting, if a user navigates deep into one tab and then switches to another, their position in the first tab is lost. Nested navigation solves this by creating isolated history stacks for different parts of the UI.

THE MENTAL MODEL Imagine your app is a building with a main lobby (the root navigator). Nested navigation is like putting an elevator inside one of the rooms. That elevator only travels between floors within that specific room; it has its own controls and doesn't affect the main lobby elevator. You can use the room's elevator, leave the room, and when you come back, the elevator is right where you left it.

HOW IT WORKS In Flutter, you create a nested navigator by placing a Navigator widget within your widget tree, typically as the body of a screen that is itself part of the main navigation flow. This new Navigator widget manages its own stack of Route objects. Any Navigator.pop or Navigator.push calls made using a BuildContext from within this sub-tree will be handled by the nested navigator, not the root one.

WHEN TO USE IT This pattern is essential for stateful tabbed navigation. The most common use case is a Scaffold with a BottomNavigationBar or TabBar, where each tab's view is a separate Navigator. This preserves the user's navigation state within each tab. It's also key for creating master-detail layouts on tablets, where selecting an item in a list on the left pushes a new screen into a navigator on the right.

WHEN NOT TO USE IT For simple, linear user flows (like a wizard or a settings page), a single global navigator is much simpler. Introducing nested navigators adds complexity to state management, deep linking, and understanding which navigator is being controlled. Avoid it unless you explicitly need to maintain separate, parallel history stacks within one screen.

ONE CANONICAL EXAMPLE A shopping app has 'Home', 'Search', and 'Cart' tabs. A user on the 'Search' tab taps a product, then another, going three screens deep. They then switch to the 'Cart' tab. When they return to the 'Search' tab, they are still on the third screen they navigated to, not back at the initial search page. This is because the body of the 'Search' tab is its own Navigator instance.

Read the original → docs.flutter.dev

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.