跳到主內容

配置 Web URL 策略

在 Web 上使用 Hash 或 Path URL 策略

Flutter Web 應用支援兩種配置 Web URL 導航的方式:

Hash(預設)

路徑的讀取和寫入均使用 Hash 片段

例如:flutterexample.dev/#/path/to/screen

Path(路徑)

路徑的讀取和寫入不帶 Hash。例如:

flutterexample.dev/path/to/screen.

配置 URL 策略

#

要將 Flutter 配置為使用路徑策略,請使用 Flutter SDK 中提供的 usePathUrlStrategy 函式,該函式位於 flutter_web_plugins 庫中。

你不能直接使用 pub add 新增 flutter_web_plugins。請將其作為 Flutter SDK 依賴項包含在你的 pubspec.yaml 檔案中。

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

然後在呼叫 runApp 之前呼叫 usePathUrlStrategy 函式。

dart
import 'package:flutter_web_plugins/url_strategy.dart';

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

配置 Web 伺服器

#

PathUrlStrategy 使用 History API,這需要對 Web 伺服器進行額外配置。

要配置你的 Web 伺服器以支援 PathUrlStrategy,請查閱伺服器文件,將請求重定向到 index.html。有關如何配置單頁應用(SPA)的詳細資訊,請檢視你所用 Web 伺服器的文件。

如果你使用的是 Firebase Hosting,請在初始化專案時選擇“Configure as a single-page app”(配置為單頁應用)選項。有關更多資訊,請參閱 Firebase 的 配置重寫(Configure rewrites)文件。

透過執行 flutter run -d chrome 建立的本地開發伺服器,已配置為能夠妥善處理任何路徑,並回退到應用的 index.html 檔案。

在非根路徑託管 Flutter 應用

#

web/index.html 中的 <base href="/"> 標籤更新為你託管應用的路徑。例如,要將你的 Flutter 應用託管在 my_app.dev/flutter_app,請將此標籤更改為 <base href="/flutter_app/">

Release 構建版本支援相對路徑的 base href 標籤,但它們必須考慮到頁面所服務的完整 URL。這意味著針對 /flutter_app//flutter_app/nested/route/flutter_app/nested/route/ 請求的相對 base href 將會有所不同(例如分別為 ".""..""../..")。