flutter 记事本-范围错误(索引):无效值:有效值范围为空:0-扑动

carvr3hs  于 2023-01-27  发布在  Flutter
关注(0)|答案(1)|浏览(129)

我想将文本和日期保存到txt文件并加载,但收到"RangeError(index):无效值:有效值范围为空:0英寸

void _loadNotes() async {
    var directory = await getApplicationDocumentsDirectory();
    var file = File("${directory.path}/notable.txt");
    if (!await file.exists()) {
      file.createSync();
      file.writeAsStringSync("Hello, World!#This is your first note.\n");
    }
    var contents = await file.readAsString();
    var contentsList = contents.split("\n");
    for (var i = 0; i < contentsList.length; i++) {
      var noteLine = contentsList[i].split("#");
      _notes.add(noteLine[0]);
      _noteAddedDates.add(noteLine[1]);
    }
  }
  void _saveNotes() async {
    var directory = await getApplicationDocumentsDirectory();
    var file = File("${directory.path}/notable.txt");
    var contents = "";
    for (var i = 0; i < _notes.length; i++) {
      contents += _notes[i] + "#" + _noteAddedDates[i] + "\n";
    }
    await file.writeAsString(contents);
  }
r55awzrz

r55awzrz1#

void _loadNotes() async {
        var directory = await getApplicationDocumentsDirectory();
        var file = File("${directory.path}/notable.txt");
        if (!await file.exists()) {
          file.createSync();
          file.writeAsStringSync("Hello, World!#This is your first note.\n");
        }
        var contents = await file.readAsString();
        var contentsList = contents.split("\n");
    Future.delayed(Duration(milliseconds: 1000), () {

//add this delay 
          for (var i = 0; i < contentsList.length; i++) {
          var noteLine = contentsList[i].split("#");
          _notes.add(noteLine[0]);
          _noteAddedDates.add(noteLine[1]);
        }                                            
            });
     
      }

相关问题