Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

dart - How to remove hash (#) from URL in Flutter web

The default URL of a Flutter web project defines a URL containing a hashtag (#), as follows:

http://localhost:41521/#/peaple/...

I would like to remove this '#', looking like this:

http://localhost:41521/peaple/

How can I solve this problem?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can now use a simple package and a single line of code to remove the leading hash (#) from your Flutter web app: url_strategy (full disclosure: I am the author)

Using url_strategy

You simply add the dependency as described here and then add the following function call to your main function:

import 'package:url_strategy/url_strategy.dart';

void main() {
  // Here we set the URL strategy for our web app.
  // It is safe to call this function when running on mobile or desktop as well.
  setPathUrlStrategy();
  runApp(MyApp());
}

Calling setPathUrlStrategy is all you need to do ??


The package also ensures that running the code will not crash on mobile (see below). Additionally, this will also run on stable if you build your mobile app on stable and only web on beta.

Notes

You need to make sure that you include <base href="/"> inside the <head> section of your web/index.html when using the path URL strategy.
This is added by default when creating a new Flutter app.

Furthermore, when deploying your production app, you need to make sure that every path points to your index.html. If you use tools like Firebase hosting, this is done automatically for you when configuring your app as a single page app.
Otherwise, you want to look up how to rewrite all paths to your index.html for the hosting you are using.

Essentially, you want to have a single page app, where the HTTP server serves the index.html for all paths.


The package implementation is based on the manual solution using flutter_web_plugins. The benefits of using the package are the following:

  • Only need to call a single function.
  • No need to use conditional imports (the package does it for you).
  • You will not get any missing implementation issues on stable (as the web feature is still on beta).

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...