当用户按下音量按钮执行特定操作并阻止默认行为(音量更改)时,我试图拦截。
这是我到目前为止的代码:
RawKeyboard.instance.addListener(_keyboardListener);
void _keyboardListener(RawKeyEvent e) {
if(e.runtimeType == RawKeyUpEvent) {
RawKeyEventDataAndroid eA = e.data;
if(eA.keyCode == 24) { //volume up key
_goNextPage();
}
if(eA.keyCode == 25) { //volume down key
_goPrevPage();
}
}
}
我将如何防止音量变化(并阻止音量 slider 出现在顶部)?
类似的 Javascript 将调用
event.preventDefault()
在关键事件上。这似乎是一件相当微不足道的事情,但我无法在文档中找到任何答案。
谢谢。
最佳答案
我遇到了类似的问题,以及如何分享我如何解决它。
要停止传播,我们必须从焦点节点树中 true
的 onKey
方法返回 FocusNode
。为了实现这一点,我用 FocusScope
和 Focus
小部件包装了我的应用程序主体,如下所示:
MaterialApp(
home: Scaffold(
body: FocusScope(
autofocus: true,
child: Focus(
autofocus: true,
canRequestFocus: true,
onKey: (data, event) {
if (event.isKeyPressed(LogicalKeyboardKey.audioVolumeUp)) {
print("Volume up");
return true;
}
if (event
.isKeyPressed(LogicalKeyboardKey.audioVolumeDown)) {
print("Volume down");
return true;
}
return false;
},
child: Text(text: "Hallochen")))))
关于events - Flutter:如何防止按键时的默认行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53473425/