Flutter,处理键盘按键事件,限制动作仅限于 keyDown

Jan*_*Jan 5 keyboard-events flutter

在 Flutter 中,我希望使用键盘事件,问题是当我按下向下键时,在 keyDown 和 keyUp 事件上都会发生操作,在代码示例中,代码将在按键时和释放按键时打印单词两次,我希望它只在 keyDown 事件上打印它并忽略 keyUp,以便在按下键并释放它后在控制台中打印一次

谢谢

   import 'package:flutter/services.dart';  //<-- needed for the keypress comparisons

FocusNode focusNode = FocusNode();  // <-- still no idea what this is.

  @override
  Widget build(BuildContext context) {
    FocusScope.of(context).requestFocus(focusNode); // <-- yup.  magic. no idea.
    return Scaffold(
        appBar: AppBar(),
        body: RawKeyboardListener(
          autofocus: true,
          focusNode: focusNode,   // <-- more magic
          onKey: (RawKeyEvent event) {
            if (event.data.logicalKey == LogicalKeyboardKey.arrowDown) {
               print(down);
               }
          },
          child: GridView.builder(
              physics: NeverScrollableScrollPhysics(),
              itemCount: 300,
              gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 30),
              itemBuilder: (BuildContext context, int index) {
                return Container(
                    padding: EdgeInsets.all(5.0),
                    color: Colors.grey,         
              },
            ),
          ),
      );
  }
Run Code Online (Sandbox Code Playgroud)

小智 1

在带遥控器的 Android TV 上测试

@override
Widget build(BuildContext context) {
    return RawKeyboardListener(
        autofocus: true,
        focusNode: FocusNode(),
        onKey:(event){
            // print(event);
            if(event is RawKeyDownEvent){ // just keyDown
                print(event.logicalKey.keyLabel); // Arrow Down || Arrow Up || Arrow Left || Arrow Right || Select || Go Back               
            }
        },
        child:Scaffold(
            appBar: AppBar(
                title: const Text('Flutter test keys'),
            ),
        ),
    );
}
Run Code Online (Sandbox Code Playgroud)