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