Configuring the URL strategy on the web
Flutter web apps support two ways of configuring URL-based navigation on the web:
- Hash (default)
- Paths are read and written to the hash fragment.
For example,
flutterexample.dev/#/path/to/screen
. - Path
- Paths are read and written without a hash. For example,
flutterexample.dev/path/to/screen
.
These are set using the setUrlStrategy
API with
either a HashUrlStrategy
or PathUrlStrategy
.
Configuring the URL strategy
The setUrlStrategy
API can only be called on the web.
The following instructions show how to use a conditional
import to call this function on the web,
but not on other platforms.
-
Include the
flutter_web_plugins
package and call thesetUrlStrategy
function before your app runs:dependencies: flutter_web_plugins: sdk: flutter
-
Create a
lib/configure_nonweb.dart
file with the following code:void configureApp() { // No-op. }
-
Create a
lib/configure_web.dart
file with the following code:import 'package:flutter_web_plugins/flutter_web_plugins.dart'; void configureApp() { setUrlStrategy(PathUrlStrategy()); }
-
Open
lib/main.dart
and conditionally importconfigure_web.dart
when thehtml
package is available, orconfigure_nonweb.dart
when it isn’t:import 'package:flutter/material.dart'; import 'configure_nonweb.dart' if (dart.library.html) 'configure_web.dart'; void main() { configureApp(); runApp(MyApp()); }
Hosting a Flutter app at a non-root location
Update the <base href="/">
tag in web/index.html
to the path where your app is hosted.
For example, to host your Flutter app at
myapp.dev/flutter_app
, change
this tag to <base href="/flutter_app/">
.