"There was no corresponding route" 通过 Flutter 网络 URL

"There was no corresponding route" through Flutter web URL

我在我的 Flutter Web 应用程序中使用命名路由进行导航。导航到所需路线时,URL 会更新,但我无法通过 URL 栏直接导航到路线。每次我尝试在 URL 中添加路径时,它都会带我到“.../#/”

使用更新的 URL 执行热重载时,出现以下错误:

Could not navigate to initial route.
The requested route name was: "/Page_One"
There was no corresponding route in the app, and therefore the initial route specified will be ignored and "/" will be used instead.
class Start extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'My Site',
      theme: ThemeData(...),
      initialRoute: '/',
      routes: <String, WidgetBuilder> {
        "/": (context) => MainPage(),
        "/Page_One": (context) => Page2(0),
        "/Page_Two": (context) => Page2(1),
        "/Page_Three": (context) => Page2(2),
      },
    );
  }
}

编辑:我也用 onGenerateRoute 尝试过,但没有成功。

EDIT2:我在生产 URL 和本地主机(例如 http://localhost:12345/#/Page_Two 上调用它们。不,localhost:12345/Page_Twolocalhost:12345/#Page_Two 也不起作用。

Edit3:我正在通过 void main() => runApp(new MaterialApp(home: Start()));

呼叫 runApp

这个呢?

class Start extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'My Site',
      theme: ThemeData(...),
      initialRoute: '/',
      routes: <String, WidgetBuilder> {
        "/": (context) => MainPage(),
        "/Page_One": (context, {p=0}) => Page2(p),
        "/Page_Two": (context, {p=1}) => Page2(p),
        "/Page_Three": (context, {p=2}) => Page2(p),
      },
    );
  }
}

这是因为您在 另一个 MaterialApp.

中 return 使用您的 Start 小部件

您 return 的第一个 MaterialApp 小部件将尝试处理传入的 URL。


所以你的结构如下:

-- entrypoint (runApp)
MaterialApp
  Start -- your widget
    MaterialApp
      // the routes live here

第一个MaterialApp没有路由,导致错误

因此,您唯一需要做的更改就是将您的结构转换为:

-- entrypoint (runApp)
Start -- your widget
  MaterialApp
    // the routes live here

代码

将您的 void main() => runApp(new MaterialApp(home: Start())); 更改为以下内容:

void main() => runApp(Start());