在 Dart 中等待按键

Wait for a keypress in Dart

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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 的以下解决方案是理想的。上面的代码缩短为:

1
2
3
4
5
6
7
8
9
10
11
12
13
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;
}

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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!结果是:

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

用法如下:

1
2
3
4
5
6
7
8
9
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
2
3
4
5
6
  Completer<KeyboardEvent> c = new Completer<KeyboardEvent>();
  sub = document.onKeyDown.listen((KeyboardEvent e){
    sub.cancel();
    c.complete(e);
  });
  return c.future;

1
  return document.onKeyDown.first;

应该这样做。

更新

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

(再次未测试)