Flutter保存文本日期到TXT文件时遇RangeError索引错误求助
解决TXT文件加载时的RangeError索引越界问题
错误根源在_loadNotes方法里,主要是两个问题导致:
- 保存笔记时每个条目末尾都加了
\n,文件最后会多出一行空内容,按\n分割后这个空字符串会被纳入contentsList - 空字符串用
#分割后得到的数组只有1个元素,强行访问noteLine[1]就会触发索引越界错误
给代码加两层校验就能解决:
- 跳过空行,不处理无内容的条目
- 确保每行分割后至少有2个元素,再存入列表
修改后的_loadNotes代码:
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 line in contentsList) { // 跳过空行 if (line.trim().isEmpty) continue; var noteLine = line.split("#"); // 校验分割后的元素数量,避免索引越界 if (noteLine.length >= 2) { _notes.add(noteLine[0]); _noteAddedDates.add(noteLine[1]); } } }
另外可以优化_saveNotes方法,避免文件末尾多出空行:
void _saveNotes() async { var directory = await getApplicationDocumentsDirectory(); var file = File("${directory.path}/notable.txt"); // 用join拼接,自动在条目间加换行,避免末尾多一个空行 var contents = List.generate(_notes.length, (i) => "${_notes[i]}#${_noteAddedDates[i]}").join("\n"); await file.writeAsString(contents); }
内容的提问来源于stack exchange,提问作者bantandor
相关产品推荐
相关产品推荐

