Flutter web: URL handling made simple with simple_url_handler

Lulupointu
3 min readJan 22, 2021

This article is part of a series aiming at making you a master of Navigator 2.0 while showing you that it is not as hard as people think. The other articles of this series are:

Do you want to deliver a good experience to you web users without having to implement many methods ? This is what the simple_url_handler package is here for.

What are we going to build?

We are going to make the counter_app up-to-date by handling the url.

The base counter app

I suppose that you are familiar with this code but I want to emphases what you have to add.

Url Handling

To handle the url with the simple_url_handler package we first have to import the package:

The we need to focus on 2 widget:

  • SimpleUrlHandler : used to map your app state and the url
  • SimpleUrlNotifier: used to notify SimpleUrlHandler that the url should be updated

There is 2 important methods to implement: urlToAppState and appStateToUrl .

urlToAppState: This method is called whenever the url is manually updated or when the user presses the forward/backward button. In our case:

  • Line 4: We try to parse the url, new counter is null if the url is not in the form of ‘/int’
  • Line 5 to 8: if the new counter is valid (not null) and it’s different from our count value, we update our count value and call setState to update the UI
  • Line 9 to 13: This is really interesting, here the url is invalid, so we don’t change the count value, however we call SimpleNotifier.of(context).notify() to update the url back to a valid one.

appStateToUrl: This is called when SimpleNotifier.of(context).notify() is used or when the SimpleUrlHandler is first created. We need to return a RouteInformation where the location attribute will be our url.

The entire code

Note that usually we would want to call SimpleNotifier.of(context).notify() in the onPressed method in order to update the url, but since we are using setState our SimpleUrlHandler will be rebuilt and therefore appStateToUrl will be called automatically.

Limitation

There are 2 main limitations to this plugin:

  • Since it uses navigator 2.0, you should use navigator 2.0 for routing as well
  • For the same reason, it is not compatible with the MaterialApp widget. You should instead use MaterialApp.router or use SimpleUrlHandler as you MaterialAppwidget. In our example we passed debugShowCheckedModeBanner: false for example.

--

--