乐闻世界logo
搜索文章和话题

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

1个答案

1

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:

  1. Add dependencies: First, ensure that flutter_web_plugins is included in your pubspec.yaml file.
yaml
dependencies: flutter: sdk: flutter flutter_web_plugins: sdk: flutter
  1. Set the URL strategy: In your main.dart file, import the necessary libraries and set UrlStrategy in the main() function. For example, using setUrlStrategy with PathUrlStrategy can remove the hash from the URL:
dart
import '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.

2024年8月8日 01:23 回复

你的答案