Flutter, handling keyboard key events, limit action just to keyDown

Viewed 1363

In Flutter, I'm looking to use keyboard events, issue is that when I press arrow down key, action happens both on keyDown and keyUp event, in code example code will print word down two times, on key press and upon releasing the key, I want it to print it just on keyDown event instead and to ignore keyUp, as to have it print in console down just once after pressing key down and releasing it

thank you

   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,         
              },
            ),
          ),
      );
  }
1 Answers

Tested on Android TV with remote control

@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'),
            ),
        ),
    );
}
Related