In Flutter web applications, the default URL strategy appends the hash (#) to the URL to handle routing correctly. This is because Flutter operates as a single-page application (SPA), and browsers need to distinguish between page navigation and resource requests. The hash marker helps the browser understand this.
However, for some applications, a more traditional URL pattern may be required where hashes are not present in the URL. To achieve this in Flutter web, you can set the URL handling strategy using UrlStrategy to remove the hash from the URL.
Starting from Flutter 2.0, you can implement the following steps:
- Add dependencies: First, ensure that
flutter_web_pluginsis included in yourpubspec.yamlfile.
yamldependencies: flutter: sdk: flutter flutter_web_plugins: sdk: flutter
- Set the URL strategy: In your
main.dartfile, import the necessary libraries and setUrlStrategyin themain()function. For example, usingsetUrlStrategywithPathUrlStrategycan remove the hash from the URL:
dartimport 'package:flutter/material.dart'; import 'package:flutter_web_plugins/flutter_web_plugins.dart'; void main() { setUrlStrategy(PathUrlStrategy()); runApp(MyApp()); } class MyApp extends StatelessWidget { Widget build(BuildContext context) { return MaterialApp( title: 'Demo App', home: HomePage(), ); } } class HomePage extends StatelessWidget { Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text("No Hash URL Demo"), ), body: Center( child: Text("Welcome to the HomePage!"), ), ); } }
After implementing these steps, when you deploy your Flutter web application, the URL will no longer contain the hash marker. This makes the URL resemble traditional web links, beneficial for SEO and more user-friendly.
Note that removing the hash may cause issues with page refreshes and proper resource location, depending on the web server configuration. Ensure your server correctly handles SPA routing requests, typically requiring the server to always return the entry page (e.g., index.html), which is handled by the client for specific routing.