Flutter -主动检查是否按下了特殊键(如ctrl)

jw5wzhpr  于 2023-05-19  发布在  Flutter
关注(0)|答案(2)|浏览(149)

问题:如何主动检查某个(装饰)键是否被按下,如CTRL或SHIFT,如:

if (SomeKeyboardRelatedService.isControlPressed()) {...}

后台

我想检查当用户单击鼠标时是否按下了某个(装饰)键。我们无法做到这一点 * 积极 *。相反,我们使用RawKeyboardListener,并记住onKey事件中的isControlPressed。这样,稍后在GestureDetector.onTap中我们可以检查isControlPressed是否是true。问题是:
1.我们自己维持按键状态似乎没有任何合理的地方,因为它违反了单一真理来源原则,并可能导致不一致。
1.它实际上是导致不一致,如果用户切换远离应用程序,而持有特殊键。
我们已经阅读了相关文档,并使用几个关键字进行了搜索,最终没有结果。

nnt7mjpx

nnt7mjpx1#

RawKeyboard可能是你正在寻找的。示例:

RawKeyboard.instance.keysPressed.contains(LogicalKeyboardKey.controlLeft)

请注意,在检查控制键等时,您需要检查所有可能的键变体。

final shiftKeys = [LogicalKeyboardKey.shiftLeft, LogicalKeyboardKey.shiftRight];
final isShiftPressed = RawKeyboard.instance.keysPressed
    .where((it) => shiftKeys.contains(it))
    .isNotEmpty;
syqv5f0l

syqv5f0l2#

我使用这个方法来检测是否按下了ctrl + v或cmd + v,以从剪贴板中获取图像

1

// declare focusNode first
final _fokusTitle = FocusNode();

...

Padding(
            padding: const EdgeInsets.all(60),
            // listen key press widget
            child: RawKeyboardListener(
              // add focus node here
              focusNode: _fokusTitle,
              child: Text("halo apa kabar , saya disini"),
              onKey: (x) async {
                // detect if ctrl + v or cmd + v is pressed
                if (x.isControlPressed && x.character == "v" || x.isMetaPressed && x.character == "v") {
                  // you need add some package "pasteboard" , 
                  // if you wan to get image from clipboard, or just replace with some handle
                  final imageBytes = await Pasteboard.image;
                  print(imageBytes?.length);
                }
              },
            ),
          )

...

Padding(
                                  padding: const EdgeInsets.all(8.0),
                                  // keyboard listener will catch some key pressed here , if you focused cursor here
                                  child: TextFormField(
                                    focusNode: _fokusTitle,
                                    controller: _controllerTitle,
                                    maxLength: 50,
                                    maxLines: 1,
                                    decoration: InputDecoration(hintText: "mulai ketik sesuatu", labelText: "judul"),
                                  ),
                                ),

相关问题