通过Dart中的循环写入文件

时间:2017-05-07 18:12:35

标签: dart dart-io

我正在尝试将一系列字符串写入文件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时,它应显示&#34; abcdefghij&#34;,而是显示&#34; j&#34;。关于我做错了什么的任何想法?我尝试了FileMode: WRITEWRITE_ONLY_APPENDWRITE_ONLY,但这些都没有。

1 个答案:

答案 0 :(得分:3)

您需要使用

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