Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter Deep Linking with Multiple Navigators

I am writing a Flutter app where I have a bottom nav bar. Each tab of the bottom nav bar has its own Navigator maintaining its own navigation stack. The main screen holds a stack of Offstage Navigators whose visibility is switched between by tapping the bottom nav tabs.

I am using the Navigator 1.0 approach to handle all my navigation.

I would like to enable deep linking in such a way that, depending on the deep link route, I can choose the appropriate bottom nav tab to select and push the MaterialPageRoute onto the Navigator responsible for that tab.

I already have the logic responsible for switching between tabs from any place within the app. I also use onGenerateRoute() to determine which route should be pushed upon receiving a deep link intent.

I would like to know if it is in any way possible to instruct a navigator other than the root navigator to push the desired route. Can this be done with using the possible parameters in MaterialApp such as onGenerateRoute or onUnknownRoute? Is this feasible without refactoring and migrating to Navigator 2.0?

like image 417
oldsport76 Avatar asked May 03 '26 08:05

oldsport76


1 Answers

Generate keys for each navigator, I'm assuming there are five.

    final _navigatorsKeys =
      List.generate(5, (index) => GlobalObjectKey<NavigatorState>('$index'));

Assign them to the respective navigators

    Navigator(
      key: _navigatorKeys[0],
        initialRoute: homeViewRoute,
        onGenerateRoute: generateRoute
    ),
    Navigator(
          key: _navigatorKeys[1],
            initialRoute: homeViewRoute,
            onGenerateRoute: generateRoute
        )...

You can them check the deep link to define to which tab it should navigate to, I suggest you prefix the links based on each navigation item. E.g.: home/post, me/profile. By doing this, you can change the tab index before navigating to the actual page.

Finally, to navigate to a page using the first navigator, you can do like this:

_navigatorsKeys[0].currentState!.pushNamed('home/posts');

Hope it helps.

like image 120
Lazaro Henrique Avatar answered May 05 '26 21:05

Lazaro Henrique