在 flutter web 上重新加载页面时“未找到”

spi*_*a95 7 dart flutter flutter-web

在 flutter web 上,当我在 Chrome 上重新加载页面时,我收到文本“未找到”。我该如何修复它?这是我的 main.dart 代码。我还注意到,要直接访问页面,我必须在 URL 中插入井号 (#),如下所示:“ http://127.0.0.1:8080/#/homepage ”。有办法去除吗?

class MyApp extends StatefulWidget {

const MyApp({Key key}): super(key: key);

@override
MyAppState createState() => MyAppState();
}

class MyAppState extends State<MyApp> {
// This widget is the root of your application.

@override
  void initState() {
  html.window.history.pushState(null, "Home", "/");
  super.initState();
}

@override
Widget build(BuildContext context) {
  return MaterialApp(
    title: 'Flutter Demo',
    initialRoute: "/",
    theme: ThemeData(
      primarySwatch: Colors.blue,
      fontFamily: 'GoogleSansRegular'
    ),
    routes: {
      "/": (context) => HomePage(),
      "/homepage": (context) => HomePage(),
      "/secondPage": (context) => SecondPage()
    },
  );
}
}
Run Code Online (Sandbox Code Playgroud)

A.K*_*.K. 0

要删除 URL 中的 #,您必须切换到设置 UrlStrategy,如此处所述的\xc2\xb4s: //docs.flutter.dev/development/ui/navigation/url-strategies

\n

长话短说:将此包(https://pub.dev/packages/url_strategy)添加到 pubspec.yaml 并在 main 方法中调用 setPathUrlStrategy() :

\n
import \'package:url_strategy/url_strategy.dart\';\n\nvoid main() {\n  // Here we set the URL strategy for our web app.\n  // It is safe to call this function when running on mobile or desktop as well.\n  setPathUrlStrategy();\n  runApp(MyApp());\n}\n
Run Code Online (Sandbox Code Playgroud)\n

也许它也能解决你的其他问题。如果没有,那么我认为使用 AutoRoute 包是个好主意:https://pub.dev/packages/auto_route

\n