flutterdartflutter-web

How to remove hash (#) from URL in Flutter web


The default URL of a Flutter web project defines a URL containing a hashtag (#), as follows:

http://localhost:41521/#/peaple/...

I would like to remove this '#', looking like this:

http://localhost:41521/peaple/

How can I solve this problem?


Solution

  • Since Flutter version 2.10.0, there is a platform-safe way to achieve this using the flutter_web_plugins package from the framework:

    Using PathUrlStrategy

    You first need to add a dependency to flutter_web_plugins from framework to your pubspec.yaml file:

    dependencies:
      flutter:
        sdk: flutter
      flutter_web_plugins:
        sdk: flutter
    

    Then, you need to make sure to import 'package:flutter_web_plugins/url_strategy.dart' (it is important that you do not import /flutter_web_plugins.dart - more on that below):

    import 'package:flutter_web_plugins/url_strategy.dart';
    

    And now you simply need to set the URL strategy in the main function of your app:

    void main() {
      // Here we set the URL strategy for our web app.
      // It is safe to call this function when running on mobile or desktop as well.
      setPathUrlStrategy();
      runApp(MyApp());
    }
    

    Calling setPathUrlStrategy is all you need to do 🎉

    Notes

    It is important to use the 'package:flutter_web_plugins/url_strategy.dart' import rather than the 'package:flutter_web_plugins/flutter_web_plugins.dart' import when calling the function in your main.dart file if you also want to use it to run your app on other platforms (mobile or desktop). Otherwise, your app will only compile for web.

    You need to make sure that you include <base href="/"> inside the <head> section of your web/index.html when using the path URL strategy.
    This is added by default when creating a new Flutter app.

    Furthermore, when deploying your production app, you need to make sure that every path points to your index.html. If you use tools like Firebase hosting, this is done automatically for you when configuring your app as a single page app.
    Otherwise, you want to look up how to rewrite all paths to your index.html for the hosting you are using.

    Essentially, you want to have a single page app, where the HTTP server serves the index.html for all paths.