有没有办法清除Flutter / Dart中的文件?我正在阅读指导并寻找使用intellisense的方法,但似乎没有 . https://flutter.io/cookbook/persistence/reading-writing-files/
目前,我的Flutter代码看起来像这样删除一个项目 .
void deleteItemInFile(Portfolio portfolio) {
if (fileExists) {
List<dynamic> portfolio_items = json.decode(jsonFile.readAsStringSync());
//putting the information into a temporary list first
List<Portfolio> temp_portfolio = new List<Portfolio>();
//now we delete the file
jsonFile.deleteSync();
for (var i = 0; i < portfolio_items.length; i++) {
if (portfolio_items[i]['time'] == widget.portfolio.time) {
//we found the item we do not want to keep
//do nothing as we want to remove this item
} else {
//the other items, we wil keep so we will put into the temp list.
temp_portfolio.add(Portfolio.fromMap(portfolio_items[i]));
}
}
//writing out all the item expect for the item we want to delete.
jsonFile.writeAsStringSync(json.encode(temp_portfolio));
}
}
-
我将当前文件中的项目保存到临时列表中 .
-
我删除了jsonFile
-
我创建了一个新列表,并通过遍历临时列表将所需项目放入该列表中
-
我将新列表写入新文件
似乎没有jsonFile.clear()方法 - 我想摆脱第2步 .
1 回答
要写一个空文件,这应该做