配置 Web 應用的 URL 策略

Flutter Web 應用支援兩種基於 URL 的路由的配置方式:

Hash(預設)
路徑使用 # + 錨點識別符號 讀寫,例如:flutterexample.dev/#/path/to/screen

Path
路徑使用非 # 讀寫,例如:flutterexample.dev/path/to/screen

配置 URL 策略

讓 Flutter 使用 path 策略,請使用 flutter_web_plugins 庫中提供的 setUrlStrategy 方法。

import 'package:flutter_web_plugins/url_strategy.dart';

void main() {
  usePathUrlStrategy();
  runApp(ExampleApp());
}

Configuring your web server

PathUrlStrategy uses the History API, which requires additional configuration for web servers.

To configure your web server to support PathUrlStrategy, check your web server’s documentation to rewrite requests to index.html.Check your web server’s documentation for details on how to configure single-page apps.

If you are using Firebase Hosting, choose the “Configure as a single-page app” option when initializing your project. For more information see Firebase’s Configure rewrites documentation.

The local dev server created by running flutter run -d chrome is configured to handle any path gracefully and fallback to your app’s index.html file.

將 Flutter 應用部署在子目錄下

更新 web/index.html 中的 <base href="/"> 標籤為你的應用部署路徑。例如:如果你期望將 Flutter 應用部署在 myapp.dev/flutter_app,則更改此標籤為 <base href="/flutter_app/">