'Overwrite file if it already exist in flutter

Is there a way to overwrite a file's content if it already exists?

For example, with the following, we write "Hello World" and follow by "Sup?". The result of the file is "Sup?o World".

File file = ...;
file.writeAsString("Hello World");
file.writeAsString("Sup?");

The closest that I find is FileMode.write or FileMode.writeOnly.

/// The file is overwritten if it already exists. The file is created 
/// if it does not already exist.

We can rename or delete the old file. But is there a better approach?



Solution 1:[1]

Why don't you simply use

File file = ...;
final buffer = StringBuffer();

buffer.write('Hello World');
buffer.write('Sup?');

file.writeAsString(buffer.toString());

Solution 2:[2]

There's an argument that you can pass in to writeAsString(); its file mode.

writeAsString(String contents, {FileMode mode = FileMode.writeOnly});

It's mentioned in the docs, that writeOnly is,

Mode for opening a file for writing only. The file is overwritten if it already exists. The file is created if it does not already exist.

file mode reference

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 iDecode
Solution 2 raul.uz