skip to Main Content

I have a Flutter app targeting Android TV devices (as well as phones), so I had to implement some special logic to handle the remote.

I wrapped buttons that need to be clicked by a remote with a Focus widget:

 Widget myButton(BuildContext context) {
   Focus(
        onKeyEvent: (node, event) {
          return manageKeyboard(event, context);
        },
          child: IconButton(
      // ... button properties here
    ),
  );
}

I wrote manageKeyboard method like this:

 KeyEventResult manageKeyboard(KeyEvent event, BuildContext context) {
    if (event.logicalKey == LogicalKeyboardKey.arrowRight) {
      if (event is KeyUpEvent) {
        doSomething(context, true);
      }
      return KeyEventResult.handled;
    }
 }

This works reasonably well. Problem is if I try to make managedKeyboard asynchrounous in order to await doSomething, I get below error in onKeyEvent:

The argument type 'Future<KeyEventResult> Function(FocusNode, KeyEvent)' can't be assigned to the parameter type 'KeyEventResult Function(FocusNode, KeyEvent)?'.

How can I make onKeyEvent asynchrounous?

2

Answers


  1. You cant assign a future callback to ‘onKeyEvent’.

    Instead, You may register a callback to ‘manageKeyboard’ as follows,

                onKeyEvent: (node, event) {
                  manageKeyboard(event, context).then((value) {
                    print(value);
                  });
                  return KeyEventResult.ignored;
                },
    

    And keep ‘manageKeyboard’ method as follows,

      Future<KeyEventResult> manageKeyboard(KeyEvent event, BuildContext context) async {
        if (event.logicalKey == LogicalKeyboardKey.arrowRight) {
          if (event is KeyUpEvent) {
            await doSomething();
            return KeyEventResult.handled;
          }
        }
     return KeyEventResult.ignored;
    }
    
    Login or Signup to reply.
  2. You can do this by onKey property with the async function.

    Focus(
      onKey: (FocusNode node, RawKeyEvent event) async {
        if (event.logicalKey == LogicalKeyboardKey.arrowRight) {
          await doSomething();
          return true;
        }
        return false;
      },
      child: Container()
    )
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search