Reputation: 19938
Is there a way to clear a file in Flutter / Dart? I was reading the guidance and looked for a method using intellisense but none seem to exist. https://flutter.io/cookbook/persistence/reading-writing-files/
Currently, my Flutter code looks like this to delete an item.
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));
}
}
I create a new list and put in that list the items I want by iterate through the temporary list
I write the new list out into a new File
There doesn't seem to be a jsonFile.clear() method - I would like to get rid of step 2.
Upvotes: 1
Views: 7949
Reputation: 657248
To write an empty file this should do
jsonFile.writeAsStringSync('');
Upvotes: 2