File.writeAsString
- Dart course
- Intermediate
- Lesson 90/116
- 5 min
Learn to write files with File.writeAsString.
Writing a string to a file
File.writeAsStringSync('text') writes a string to a file. By default it writes from scratch (overwrites). With FileMode.append you add to the end.
Example: f.writeAsStringSync('new line', mode: FileMode.append) appends 'new line' to the file. It does not overwrite.
flush: true makes the write hit the disk immediately. By default Dart buffers writes.
Overwrite and append
Overwrite erases the old content and places the new. Append keeps the old content and writes at the end. Choosing the right mode prevents data loss.
For example when logging you use FileMode.append to add each day's record at the end. Overwrite is wanted only when building the file from scratch.
When writing twice to the same file use await or a sync method; avoid partial writes.
Practice Append two lines
Import the library with import 'dart:io';. In main create File('log.txt'). First write with writeAsStringSync('first'). Then append with writeAsStringSync(' second', mode: FileMode.append). Then read with readAsStringSync() and print it with print.
Starter code
// Import the dart:io library
void main() {
// write to log.txt, append, read and print
}Sample solution
import 'dart:io';
void main() {
var f = File('log.txt');
f.writeAsStringSync('first');
f.writeAsStringSync(' second', mode: FileMode.append);
print(f.readAsStringSync());
}Expected output
first second
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Append mode
f.writeAsStringSync('metin', mode: ____);
f.writeAsStringSync('metin', mode: FileMode.append);
Explanation: FileMode.append appends to the end.
2 What is the default behavior of writeAsStringSync?
- Overwrites Correct answer
- Throws
- Appends
- Deletes the file
Explanation: by default it overwrites the file.
3 Writing parts
| Term | Meaning |
|---|---|
writeAsStringSync() |
Sync writing |
FileMode.append |
Appending |
FileMode.write |
Overwriting |
flush: true |
Flush buffer |