问题:如何主动检查是否按下了某个(装饰)键,如CTRL或SHIFT,如:
if (SomeKeyboardRelatedService.isControlPressed()) {...}
我想检查当用户单击鼠标时是否按下了某个(装饰)键。我们无法做到 active。 相反,我们使用
RawKeyboardListener
并记住 isControlPressed
在 onKey
事件中。这样,稍后在GestureDetector.onTap
我们可以检查isControlPressed
是否是true
。问题是:
我们看了相关的文档,用了几个关键词搜索,都没有结果。
RawKeyboard 可能是您正在寻找的。例子:
RawKeyboard.instance.keysPressed.contains(LogicalKeyboardKey.controlLeft)
请注意,在检查控制键等时,您需要检查所有可能的键变体
final shiftKeys = [LogicalKeyboardKey.shiftLeft, LogicalKeyboardKey.shiftRight];
final isShiftPressed = RawKeyboard.instance.keysPressed
.where((it) => shiftKeys.contains(it))
.isNotEmpty;
我用这个方法来检测是否按下了 ctrl + v 或 cmd + v,从剪贴板中获取图像
// 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"),
),
),