跳到主內容

在網頁上配置 URL 策略

在 Web 上使用雜湊或路徑 URL 策略

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

雜湊 (預設)

路徑被讀取和寫入到 雜湊片段

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

路徑

路徑被讀取和寫入,不帶雜湊。例如,

flutterexample.dev/path/to/screen.

配置 URL 策略

#

要配置 Flutter 使用路徑,請使用 usePathUrlStrategy 函式,該函式由 Flutter SDK 的 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,請查閱您的 Web 伺服器文件,以將請求重寫到 index.html。請查閱您的 Web 伺服器文件,瞭解如何配置單頁應用程式的詳細資訊。

如果您使用的是 Firebase Hosting,請在初始化專案時選擇“配置為單頁應用程式”選項。有關更多資訊,請參閱 Firebase 的 配置重寫 文件。

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

在非根位置託管 Flutter 應用

#

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

相對 base href 標籤在釋出構建中受支援,但它們必須考慮到頁面實際服務的完整 URL。這意味著對 /flutter_app//flutter_app/nested/route/flutter_app/nested/route/ 的相對 base href 將不同(例如,分別為 ".""..""../..")。