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));
    }
  }
  1. I save the items within my current file into a temporary list.
  2. I delete the jsonFile
  3. I create a new list and put in that list the items I want by iterate through the temporary list

  4. 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.


Solution 1: Günter Zöchbauer

To write an empty file this should do

jsonFile.writeAsStringSync('');


Solution 2: Ronan

You can all use this: jsonFile.writeAsString('');