如何在Dart中调度KeyEvent(模拟键入)?

时间:2014-02-18 13:11:46

标签: dart

我们如何在Dart中生成和发送关键事件(" keypress"," keyup"," keydown")?

我试过了:

// 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

最后一句话导致:

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

异常报告ev不是Event的实例,但是从打印输出中我们看到它是。{/ p>

1 个答案:

答案 0 :(得分:3)

显然,这被认为是一个错误:Dart Issue #16869, "Cannot dispatch KeyEvent"。一旦修复,我将发布更新。

我在此期间找到的唯一解决方案是使用 TextEvent 模拟重复按键事件。这是我使用的辅助函数

  /**
   * 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));
  }