通过 Dart 中的循环写入文件

Writing to a file through a loop in Dart

我正在尝试将一系列字符串写入文件,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);
   }
 }

当打开文件Letters.txt时,它应该显示"abcdefghij",但是却显示"j"。关于我做错了什么的任何想法?我尝试了 FileMode: WRITEWRITE_ONLY_APPENDWRITE_ONLY,但其中 none 也有效。

您需要使用

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

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