在 Flutter Web 中禁用转义键导航

Dan*_*fin 5 flutter flutter-web

当在 Flutter web 上输入 escape 键时,Flutter 会执行Navigator.of(context).pop(). 如何禁用此功能?

以下是我测试的场景,所有这些场景都产生了一致的功能:

  • Mac 上的 Chrome、Windows 上的 Edge 以及 DartPad 1.20.0
  • MaterialAppCupertinoApp, 和WidgetsApp
  • 调试模式和发布模式

我可以使用 禁用它WillPopScope,但这也禁用了按浏览器中的后退按钮。我仍然希望允许用户使用浏览器进行导航,因此这不是一个可行的选择。

附带问题:有谁知道为什么这是默认功能?这不是网站上的预期行为(不包括弹出菜单)。

Spa*_*atz 5

Flutter Web(以及桌面)使用Esc快捷方式来关闭模式对话框或弹出菜单。此绑定是在WidgetsApp.defaultShortcuts中的应用程序级别定义的,不幸的是,它也会影响 Navigator。当然,页面之间的导航键盘快捷键应该有所不同,但目前Flutter Web状态为测试版,某些功能仍在开发中。

作为解决方法,我们可以从以下位置删除此快捷方式MaterialApp

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    final shortcuts = Map.of(WidgetsApp.defaultShortcuts)
      ..remove(LogicalKeySet(LogicalKeyboardKey.escape));
    return MaterialApp(
      shortcuts: shortcuts,
      home: HomePage(),
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

并且必须根据需要在本地恢复一个:

  Future<void> openDialog(BuildContext context) async {
    final shortcuts = Shortcuts.of(context).shortcuts;
    final key = LogicalKeySet(LogicalKeyboardKey.escape);
    shortcuts[key] = WidgetsApp.defaultShortcuts[key];
    await showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text("Alert Dialog"),
          content: Text("Dialog Content"),
        );
      },
    );
    shortcuts.remove(key);
  }
Run Code Online (Sandbox Code Playgroud)