mbreton
mbreton

Reputation: 684

How to trigger a KeyboardEvent in Dart

Like I said in the title, I would like to simulate a keyup event in Dart. The problem is that I have not found how create a new KeyboardEvent object.

The only way that I've found is to use the Event(String type) constructor and then dispatch it on window object. But that doesn't work because of my "keyup" handler who takes a KeyboardEvent in parameter. Example:

window.on.keyUp.add((KeyboardEvent e){
 print('keyUp handler');
});
KeyboardEvent e = new Event("KeyboardEvent");
window.on.keyUp.dispatch(e);

Is there a way to create and dispatch a KeyBoardEvent to simulate a "keyup" in Dart?

Also, I should mention that I tried too to trigger the event in JavaScript, thanks to js-interop library, but it only fires the JS handlers.

Upvotes: 4

Views: 2940

Answers (2)

mbreton
mbreton

Reputation: 684

It's possible now to Dispatch a KeyBoardEvent from window, please see discussion on Google Group for more information: https://groups.google.com/a/dartlang.org/d/topic/misc/mgnd1TUGn68/discussion

Upvotes: 0

Eduardo Copat
Eduardo Copat

Reputation: 5151

Try the following code:

window.on.keyUp.add((Event event){
    print('keyUp handler');

    if(event is KeyboardEvent)
    {
      KeyboardEvent keyEvent = event as KeyboardEvent;
      //do stuff with keyEvent if needed
    }  
});

window.on.keyUp.dispatch(new Event("keyup"));

I think the parameter on the Event constructor must be the type of the event. Also, you can check if the event is a keyboardEvent, so you can handle KeyIdentifier, for example.

Upvotes: 1

Related Questions