dartdart-io

Writing to a file through a loop in Dart


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.


Solution

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