EN VI

Flutter - How to write letter by letter in Dart?

2024-03-17 01:00:08
Flutter - How to write letter by letter in Dart?

I'm a very beginner to Dart and am trying to write a function that prints a string letter by letter with there being a delay between every letter. It works for the most part, however, it gives me some issues when using this function more than 1 time because of the Future.delayed.

This is my code:

void printFancy(data) {

    List sample = data.split("");

    print(data);
    print(sample);

    sample.asMap().forEach((index, element) {

        Future.delayed(Duration(milliseconds: index*50), () {
            stdout.write(element.toString());
        });

    });

    stdout.write("\n");

}

Solution:

Your code printouts simultaneously without awaiting their completion, leading to overlapping outputs

use asynchronous execution with awaited delays

Future<void> printFancy(String data) async {
   List<String> sample = data.split("");


   for (var element in sample) {
     await Future.delayed(Duration(milliseconds: 50));
     stdout.write(element);
   }

    stdout.write('\n');
  }

  void main() async {
    await printFancy("Hello");
    await printFancy("World");
 }
Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login