【问题标题】:How to ignore invalid named routes in flutter?如何在颤动中忽略无效的命名路由?
【发布时间】:2021-04-01 08:53:34
【问题描述】:

我有一个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 级别进行设置吗?

【问题讨论】:

  • 你尝试过 try and catch 方法吗?
  • 我本可以尝试的,但我不喜欢它。该错误很常见 FlutterError(不是某些特定的“NavigationError”或“RouteDoesNotExist”)。此外,我想在路由器(导航器、应用程序)级别进行设置,而不是在我想导航到某些可能是路由的字符串的每个地方。

标签: flutter flutter-navigation


【解决方案1】:

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

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 时简单地阻止导航(绝对是我推荐的,但我想你有你的理由),这看起来像另一种选择。

【讨论】:

  • 感谢您的回复!试过了,但是 Scaffold 没有显示空的 Container(),所以即使是动画也不可见!看起来有点hacky,但非常有用。
猜你喜欢
  • 2020-12-12
  • 1970-01-01
  • 2014-04-10
  • 2019-01-10
  • 2015-03-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-25
相关资源
最近更新 更多