Updating URL from TabBar selection

Viewed 177

I'm currently working on updating a Flutter Web app to support sharing pages via URLs. I currently have a screen that uses a TabBar, and shows different views based on the selected tab. I want to be able to do two things:

  • Update the URL when a tab is selected (e.g. append &section=tabName to the URL)
  • Paste the URL into a new browser tab and have the application open on the tab specified by the URL

The second part of this was simple enough, just take the &section=... argument and use that to set the initialIndex of the tab controller. Updating the URL however seems quite difficult.

I've tried using RouteInformationParser to generate a new route from a list of arguments, but that triggers the onGenerateRoute callback and just seems to re-navigate to the page with the initialIndex updated from the new URL. I can get around this by replacing the TabBarView with a nested Navigator that navigates to the selected tab's content, but it seems like this could quickly become quite clunky if you wanted to navigate deeper than just a selected tab.

A simpler option I've seen mentioned is window.history.replaceState, which seems a lot simpler but feels like a bit of a kludge. Are there any ways of doing this that I've missed?

Thanks!

1 Answers

It's a little hacky, but I was able to force a URL change on tabbed navigation by using the TabBar.onTap, which provides the tab index, and having navigation happen through that. It ruined the nice slide action, but I got the custom URL in the address bar, which was more important for my use.

Related