我正在尝试用 Dart 制作一个简单的角色扮演游戏。我需要在屏幕上的 div 中显示文本,并且我需要让程序在显示下一段文本之前等待用户输入。
例如:
void main() {
showText("Hello, Adventurer! Welcome to the land of Dartia! (Press ENTER to continue...)");
print("showText has finished");
}
“showText has finished”
在文本显示完毕且玩家按下 enter 之前不应显示。这是我目前拥有的(在我看来相当丑陋的)代码:
void showText(String text) {
var textBox = querySelector("#sample_text_id")
..text = "";
var timer;
var out;
out = ([int i = 0]) {
textBox.text += text[i];
if (i < text.length - 1) timer = new Timer(const Duration(milliseconds: 10), () => out(i + 1));
};
out();
}
Timer 异步运行 out()
函数,我不希望它这样做。理想情况下,我想写这样的东西:
void showText(String text) {
var textBox = querySelector("#sample_text_id")
..text = "";
for(int i = 0; i < text.length; i++) {
textBox.text += text[i];
pause(const Duration(milliseconds: 10)); // pause the program for given duration
}
waitFor(KeyEnum.ENTER, KeyStateEnum.DOWN); // pause until key is pressed (pseudo Enum contains char codes)
}
这可能吗?
最佳答案
下面是一个示例,说明如何使用新的异步/等待功能执行此操作。请注意方法主体开头的异步声明,以及调用 pause() 和 showText() 之前的 await 语句。
Future pause(Duration d) => new Future.delayed(d);
Future waitFor(int c) => document.body.onKeyDown.firstWhere((e) => e.keyCode == c);
Future showText(String text) async {
var textBox = querySelector("#sample_text_id")
..text = "";
for(int i = 0; i < text.length; i++) {
textBox.text += text[i];
await pause(const Duration(milliseconds: 100)); // pause the program for given duration
}
return waitFor(KeyCode.ENTER); // pause until key is pressed
}
main() async {
await showText("Hello, Adventurer! Welcome to the land of Dartia! (Press ENTER to continue...)");
print("showText has finished");
}
关于html - 我可以为设定的时间或输入创建 Dart 函数 "wait"吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27245812/