如何忽略 flutter 中的无效命名路由?

How to ignore invalid named routes in flutter?

我有一个 MateriallApp,只有很少的路由和 onGenerateRoute 回调。当我在 Navigator.pushNamed 中推送无效路由时,它抛出一个错误提示

Unhandled Exception: Could not find a generator for route RouteSettings("/path", null) in the _WidgetsAppState.
E/flutter ( 2342): Make sure your root app widget has provided a way to generate
E/flutter ( 2342): this route.
E/flutter ( 2342): Generators for routes are searched for in the following order:
E/flutter ( 2342):  1. For the "/" route, the "home" property, if non-null, is used.
E/flutter ( 2342):  2. Otherwise, the "routes" table is used, if it has an entry for the route.
E/flutter ( 2342):  3. Otherwise, onGenerateRoute is called. It should return a non-null value for any valid route not handled by "home" and "routes".
E/flutter ( 2342):  4. Finally if all else fails onUnknownRoute is called.
E/flutter ( 2342): Unfortunately, onUnknownRoute was not set.

在我设置 onUnknownRoute 回调后,它说:

When the _WidgetsAppState requested the route RouteSettings("/path", null) from its onUnknownRoute callback, the callback returned null. Such callbacks must never return null.

但如果路线无效,我不想导航到任何地方(因此用户停留在同一屏幕上)。

问题来了:如何忽略中断的路由?有什么方法可以在 MaterialApp 级别上进行设置吗?

这很疯狂,但如果您只是执行以下操作会怎样:

onUnknownRoute: (settings) {
  return MaterialPageRoute<void>(
    settings: settings,
    builder: (BuildContext context) {
        Navigator.pop(context);
        return Scaffold(body: Center(child: Text('Not Found'))); // This should never really be seen.
    },
  );
},

你会留下丑陋的屏幕过渡效果,但除非我们在调用 pushNamed 时简单地阻止导航(绝对是我推荐的,但我想你有你的理由) ,这似乎是另一种选择。