How to dispatch an KeyboardEvent with specific Key

2019-07-23 14:47发布

问题:

I try to dispatch an keyboard event for the esc key (for testing) this is what i got so far:

  KeyboardEvent keyEvent = new KeyboardEvent('keypress');

  window.onKeyPress.listen((KeyboardEvent event){
    KeyEvent keyEvent = new KeyEvent.wrap(event);
    if(keyEvent.keyCode == KeyCode.ESC){
      //do stuff
    }
  });

  window.dispatchEvent(keyEvent);

This works as expected. The onKeyPress listener triggers.

But i didn't find out how to set a KeyCode for my KeyBoardEvent?

回答1:

Can't use dispatchEvent. Try:

import 'dart:async';
import 'dart:html';

void main() {
  Stream stream = KeyEvent.keyPressEvent.forTarget(document.body);
  stream.listen((KeyEvent keyEvent){
    if(keyEvent.keyCode == KeyCode.ESC) {
        // do stuff
    }
  });
  stream.add(new KeyEvent('keypress', keyCode: KeyCode.ESC));
}

as described in https://api.dartlang.org/apidocs/channels/stable/dartdoc-viewer/dart:html.KeyEvent