Patrice Chalin
Patrice Chalin

Reputation: 16100

How to dispatch a KeyEvent (to simulate typing) in Dart?

How can we generate and dispatch a key event ("keypress", "keyup", "keydown") in Dart?

I have tried:

// Context: import 'dart:html' as dom;
...
InputElement input = dom.querySelector(...);
var ev = new KeyEvent('keypress', keyCode: 65);
print("ev=$ev, and (ev is Event) is ${ev is Event}");
  // ==> output: ev=Instance of 'KeyEvent', and (ev is Event) is true
input.dispatchEvent(ev);
  // ==> yields

The last statement causes:

Caught Invalid class: expected instance of Event
#0      Node.dispatchEvent (.../dart/dart/html/Node.dart:586)

The exception reports that ev is not an instance of Event and yet from the printed output we see that it is.

Upvotes: 4

Views: 651

Answers (1)

Patrice Chalin
Patrice Chalin

Reputation: 16100

Apparently, this is recognized as a bug: Dart Issue #16869, "Cannot dispatch KeyEvent". Once this is fixed I will post an update.

The only solution I have found in the meantime is to simulate repeated keypress events by making use of TextEvent. Here is a helper function I used

  /**
   * This function simulates typing the given value string into the input
   * field. It has the side-effect of setting the window focus to the input.
   */
  void setInputValueViaTextEvent(InputElement input, String value) {
    input..focus()
         ..dispatchEvent(new TextEvent('textInput', data: value));
  }

Upvotes: 3

Related Questions