在Dart等待按键

时间:2014-12-20 20:19:54

标签: dart dart-html

我希望暂停执行我的Dart脚本(在网页中),直到用户点击密钥为止。以下代码有效,但我想知道是否有更好的方法:

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

StreamSubscription sub;

Future main() async {
  KeyboardEvent k = await getkey();
  print(k.keyCode.toString());
}

Future<KeyboardEvent> getkey() async {
  Completer<KeyboardEvent> c = new Completer<KeyboardEvent>();
  sub = document.onKeyDown.listen((KeyboardEvent e){
    sub.cancel();
    c.complete(e);
  });
  return c.future;
}

更新:Gunter的解决方案非常理想。上面的代码缩短为:

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

StreamSubscription sub;

Future main() async {
  KeyboardEvent k = await getkey();
  print(k.keyCode.toString());
}

Future<KeyboardEvent> getkey() async {
  return document.onKeyDown.first;
}

但是,如果我想过滤按键,我想我会回到以前的风格:

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

StreamSubscription sub;

Future main() async {
  KeyboardEvent k = await getkey([KeyCode.A,KeyCode.B,KeyCode.C,KeyCode.D]);
  print(k.keyCode.toString());
}

Future<KeyboardEvent> getkey([List<int> lst]) async {
  Completer<KeyboardEvent> c = new Completer<KeyboardEvent>();
  sub = document.onKeyDown.listen((KeyboardEvent e){
    if ((lst==null)||(lst.contains(e.keyCode))){
      sub.cancel();
      c.complete(e);
    }
  });
  return c.future;
}

是吗?

更新再次感谢Gunter!结果是:

Future<KeyboardEvent> getkey([List<int> lst]) async {
  return document.onKeyDown.firstWhere((KeyboardEvent e)=>((lst==null)||(lst.contains(e.keyCode))));
}

使用如下:

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

Future main() async {
  KeyboardEvent k = await getkey();
  print(k.keyCode.toString());
  KeyboardEvent k = await getkey([KeyCode.A,KeyCode.B,KeyCode.C,KeyCode.D]);
  print(k.keyCode.toString());
}

1 个答案:

答案 0 :(得分:1)

未经测试,但据我记得更改

  Completer<KeyboardEvent> c = new Completer<KeyboardEvent>();
  sub = document.onKeyDown.listen((KeyboardEvent e){
    sub.cancel();
    c.complete(e);
  });
  return c.future;

  return document.onKeyDown.first;

也应该这样做。

更新

  return document.onKeyDown.firstWhere((KeyboardEvent e) => 1st.contains(e.keyCode));

(再次未经测试)