Codementor Events

Remove ‘#’ from URL in Flutter: HashUrlStrategy and PathUrlStrategy

Published Aug 05, 2021
Remove ‘#’ from URL in Flutter: HashUrlStrategy and PathUrlStrategy

Now, it might have come in your sight that ‘#’ appearing on your hosted flutter app URL. Now it is quite annoying when this happens.
http://localhost:56235/#/login
But, there is a way that can help you vanish this ‘#’ from your URL.
Flutter web apps basically supports two different ways of configuring URL-based navigation on the web:
Hash (By Default)
Here, the hash fragment is read and written with a path.
For example;
http://localhost:56235/#/login
Path
Without a hash, paths can be read and written.
For example;
http://localhost:56235/#/login
These are set using setUrlStratgy API with either a PathUrlStrategy or HashUrlStrategy.
The setUrlStrategy can only be called on the web. Here, these instructions will show how to use the conditional import in order to call the function on the web.
The setUrlStrategy API is only accessible via the web. The instructions below show how to invoke this function via a conditional import on the browser, but not on other platforms.

  1. Before your programme launches, include the flutter_web_plugins package and call the setUrlStrategy function:
 dependencies:
    flutter_web_plugins:
      sdk: flutter

  1. Create a lib/configue_nonweb.dart file with the code given below:
void configureApp() {
    		// No-op.
  }

  1. Create a lib/configure_web.dart file using following code:
void configureApp() {
    		setUrlStrategy(PathUrlStrategy());
 	 }

  1. Open lib/main.dart and conditionally import configue_web.dart when the html package, or configure_nonweb.dart when it isn’t:
void main() {
 
    		configureApp();
  		runApp(MyApp());
}

The ‘#’ fragments are generally used in web applications to point to a secondary resource. A secondary resource could be a particular paragraph, section or header in the web app. The HashUrlStrategy or PathUrlStrategy is used by default for flutter web applications.
You can use methods from the HashUrlStrategy class to return the active path, current state and to push, replace and move in between history entries. However if you still need to remove the ‘#’ from the url it can be done with the PathUrlStartegy class. Update your main.dart as provided to remove the #.
You can also do it by simply doing this:

void main() {
  setUrlStrategy(PathUrlStrategy());
  runApp(MyApp());

Discover and read more posts from Pritesh Modi
get started