Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing to a file through a loop in Dart

Tags:

dart

dart-io

I am trying to write a series of Strings into a file, Letters.txt.

 import "dart:io";

 main() {
   List letters = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k"];
   File file = new File("Letters.txt");
   for (int i = 0; i < 10; i++) {
     file.writeAsString("${letters[i]}", mode: FileMode.APPEND);
   }
 }

When opening the file, Letters.txt, it should show "abcdefghij", but instead, it shows "j". Any ideas on what I am doing wrong? I tried FileMode: WRITE, WRITE_ONLY_APPEND, and WRITE_ONLY, but none of those worked either.

like image 316
richalot Avatar asked Feb 04 '23 12:02

richalot


1 Answers

You need to use

 file.writeAsStringSync("${letters[i]}", mode: FileMode.append);

or

main() async {
  List letters = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k"];
  File file = new File("Letters.txt");
  for (int i = 0; i < 10; i++) {
    await file.writeAsString("${letters[i]}", mode: FileMode.append);
  }
}
like image 187
Günter Zöchbauer Avatar answered Feb 07 '23 02:02

Günter Zöchbauer