配置 Web 应用的 URL 策略

Flutter Web 应用支持两种基于 URL 的路由的配置方式:

Hash(默认)
路径使用 # + 锚点标识符 读写,例如:flutterexample.dev/#/path/to/screen

Path
路径使用非 # 读写,例如:flutterexample.dev/path/to/screen

配置 URL 策略

让 Flutter 使用 path 策略,请使用 flutter_web_plugins 库中提供的 setUrlStrategy 方法。

setUrlStrategy API 只能在 Web 平台使用。下方的内容将介绍如何在 Web 平台下(仅在 Web 平台可用)使用条件引入的方式来调用此方法。

设置 Web 平台

首先,将插件 flutter_web_plugins 加入到工程的 pubspec.yaml 文件中:

dependencies:
  flutter_web_plugins:
    sdk: flutter

runApp() 之前调用 setUrlStrategy:

import 'package:flutter/material.dart';
import 'package:flutter_web_plugins/flutter_web_plugins.dart';

void main() {
  setUrlStrategy(PathUrlStrategy());
  runApp(MyApp());
}

Cross platform setup

If your app is cross-platform, use Dart’s conditional imports feature by creating three files:

url_strategy.dart

export 'url_strategy_noop.dart' if (dart.library.html) 'url_strategy_web.dart';

url_strategy_noop.dart

void usePathUrlStrategy() {
  // noop
}

url_strategy_web.dart

import 'package:flutter_web_plugins/flutter_web_plugins.dart';

void usePathUrlStrategy() {
  setUrlStrategy(PathUrlStrategy());
}

Then, call setPathUrlStrategy before runApp():

main.dart

import 'package:flutter/material.dart';
import 'url_strategy.dart';

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

Using conditional imports ensures that the flutter_web_plugins library is only loaded when your app is running on the web.

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/">