Search code examples
htmldartwait

Can I make a Dart function "wait" for a set amount of time or input?


I'm trying to make a simple RPG in Dart. I will need to show text on a screen in a div, and I need to make the program wait for user input before displaying the next piece of text.

For example:

void main() {
  showText("Hello, Adventurer! Welcome to the land of Dartia! (Press ENTER to continue...)");
  print("showText has finished");
}

"showText has finished" should not display until the text has been displayed and the player presses enter. Here's the (pretty ugly in my opinion) code I have so far:

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();
}

The Timer runs the out() function asynchronously, which I don't want it to do. Ideally I would like to write something like this:

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)
}

Is this possible?


Solution

  • Here's an example of how to do this using the new async/await feature. Note the async declaration at the start of method bodies, and the await statement before the call to pause() and showText().

    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");
    }