dart Flutter Web:在物理键盘按键上执行操作

x6h2sr28  于 4个月前  发布在  Flutter
关注(0)|答案(1)|浏览(39)

在Flutter Web中,我显示一个带有两个操作的弹出窗口“取消”&“确认”。通常,按物理键盘上的ESC键将弹出窗口从框中删除。我想通过按物理键盘上的ENTER键执行确认功能。
我采用了RawKeyboard方法,但似乎不起作用。下面是我的尝试。

showDialog(
      context: context,
      builder: (context) {
        return RawKeyboardListener(
          focusNode: FocusNode(),
          onKey: (RawKeyEvent event){
            print("keyboard key is pressed");
            if(event.isControlPressed){
              print('controlled pressed');
            }
            if (event is RawKeyDownEvent) {
              print('Pressed Key: ${event.logicalKey.debugName}');
            }
            if(event.isKeyPressed(LogicalKeyboardKey.enter)){
              print("Enter is pressed");
            }
          },
          child: DialogSimple(
            title: "Delete Category?",
            message:
            "Do you really want to delete this category?. You cannot undo this action.",
            actions: [
              BtnTextAccent(
                text: "Cancel",
                textColor: Colors.white,
                onPressed: () => Navigator.pop(context),
              ),
              BtnTextAccent(
                text: "Delete",
                textColor: AppColors.dangerColor,
                onPressed: () {
                  Navigator.pop(context);
                  cubit.deleteCategory(item.id);
                },
              ),
            ],
          ),
        );
      });

字符串
上面的代码并没有检测到任何按键事件。我是不是漏掉了什么?

rlcwz9us

rlcwz9us1#

与其直接在showDialog方法中创建FocusNode示例,不如直接在有状态小部件中创建一个示例(不要忘记释放它)

final FocusNode _focusNode = FocusNode();

  @override
  void dispose(){
    _focusNode.dispose();
    super.dispose();
  }

字符串
然后,在返回RawKeyboardWidget之前请求焦点:

showDialog(
        context: context,
        builder: (context) {
          Future.microtask(() => _focusNode.requestFocus());
          return RawKeyboardListener(
            focusNode: _focusNode,
            onKey: (RawKeyEvent event){
              print("keyboard key is pressed");
              if(event.isControlPressed){
                print('controlled pressed');
              }
              if (event is RawKeyDownEvent) {
                print('Pressed Key: ${event.logicalKey.debugName}');
              }
              if(event.isKeyPressed(LogicalKeyboardKey.enter)){
                print("Enter is pressed");
              }
            },
            child: ... whatever child you want to put in there

相关问题