Home > Back-end >  How to remove previous printed line from Console in Dart
How to remove previous printed line from Console in Dart

Time:07-09

How I can remove previously printed line in console with print() in Dart?

I am willing to display a progress indicator such as:

int n = 0;
for (var item in list) {
  n  ;
  print('${(n / list.length * 100).toStringAsFixed(0)}%');
  // do something
}

Currently it prints:

1%
2%
3%
...

But I would like to delete the previous line and replace it with the newly calculated percent.

CodePudding user response:

You can use dart:io and a carriage return (\r):

import "dart:io";

void main() {
  for (int i = 0; i < 5; i  ) {
    stdout.write("\r $i");
  }
}

CodePudding user response:

print always adds a newline, but you can write directly to stdout to avoid that.

To overwrite the previous line, you can place a carriage return ('\r') character at the start of your string, which tells the cursor to return to the beginning of the line. You may also want to pad the end of your string with some spaces to overwrite any text which might still be remaining from the previous write, although that's not necessary in this case.

It may look something like this in the end:

// At top of file
import 'dart:io';

int n = 0;
for (var item in list) {
  n  ;
  stdout.write('\r${(n / list.length * 100).toStringAsFixed(0)}%');
  // do something
}
  •  Tags:  
  • dart
  • Related