zl程序教程

您现在的位置是:首页 >  移动开发

当前栏目

Flutter 监听键盘

flutter 监听 键盘
2023-09-27 14:27:38 时间

可以使用 

RawKeyboardListener 包裹一层
    body: RawKeyboardListener(
          focusNode: FocusNode(),
          autofocus: true,
          onKey: (event) {
            if (event.runtimeType == RawKeyDownEvent) {
              Direction newDirection = Direction.Left;

              switch (event.logicalKey.keyLabel) {
                case "Arrow Up":
                  newDirection = Direction.Up;
                  break;
                case "Arrow Down":
                  newDirection = Direction.Down;
                  break;
                case "Arrow Left":
                  newDirection = Direction.Left;
                  break;
                case "Arrow Right":
                  newDirection = Direction.Right;
                  break;
              }
              setState(() {
                direction = newDirection;
              });
            }
          },
          child: _body(),
        )