在 Flutter Web 中禁用转义键导航
Disable escape key navigation in Flutter Web
在 Flutter web 上输入转义键时,Flutter 执行 Navigator.of(context).pop()
。我怎样才能禁用此功能?
以下是我测试的场景,它们都产生了一致的功能:
- Chrome 在 Mac、Edge 在 Windows 和 DartPad 1.20.0
MaterialApp
、CupertinoApp
和 WidgetsApp
- 调试模式和发布模式
我可以使用 WillPopScope
禁用它,但这也会禁用浏览器中的后退按钮。我仍然希望允许用户使用浏览器进行导航,所以这不是一个可行的选择。
附带问题:有人知道为什么这是默认功能吗?这不是网站上的预期行为(不包括弹出菜单)。
Flutter web(还有桌面)使用 Esc 快捷方式关闭模态对话框或弹出菜单。此绑定是在 WidgetsApp.defaultShortcuts 中的应用程序级别定义的,不幸的是,它也会影响 Navigator。当然,对于页面之间的导航,键盘快捷键应该有所不同,但目前 Flutter web 状态为 beta,一些功能仍在开发中。
作为解决方法,我们可以从 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(),
);
}
}
并且必须根据需要在本地恢复一个:
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);
}
在 Flutter web 上输入转义键时,Flutter 执行 Navigator.of(context).pop()
。我怎样才能禁用此功能?
以下是我测试的场景,它们都产生了一致的功能:
- Chrome 在 Mac、Edge 在 Windows 和 DartPad 1.20.0
MaterialApp
、CupertinoApp
和WidgetsApp
- 调试模式和发布模式
我可以使用 WillPopScope
禁用它,但这也会禁用浏览器中的后退按钮。我仍然希望允许用户使用浏览器进行导航,所以这不是一个可行的选择。
附带问题:有人知道为什么这是默认功能吗?这不是网站上的预期行为(不包括弹出菜单)。
Flutter web(还有桌面)使用 Esc 快捷方式关闭模态对话框或弹出菜单。此绑定是在 WidgetsApp.defaultShortcuts 中的应用程序级别定义的,不幸的是,它也会影响 Navigator。当然,对于页面之间的导航,键盘快捷键应该有所不同,但目前 Flutter web 状态为 beta,一些功能仍在开发中。
作为解决方法,我们可以从 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(),
);
}
}
并且必须根据需要在本地恢复一个:
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);
}