File.readAsString
- Dart course
- Intermediate
- Lesson 89/116
- 5 min
Learn to read files with File.readAsString.
Reading a file as a string
File.readAsStringSync() reads a file's full content as a string. It is synchronous; the program waits until done. Write to the file first, then read.
The async readAsString() returns a Future<String>; you wait with await. For small files the synchronous version is simpler.
If the file is missing the read throws. So checking with existsSync() first is safer.
Encoding
readAsStringSync() uses UTF-8 encoding by default. Special characters read correctly. You can pass another encoding with readAsStringSync(encoding: latin1).
Writing with writeAsStringSync('text') also uses UTF-8. Inconsistent encoding garbles characters and makes them unreadable.
Dart strings are Unicode based; emojis and special letters travel safely. As long as the file is encoded right, the letters stay intact.
Practice Write then read
Import the library with import 'dart:io';. In main create File('data.txt'); write with writeAsStringSync('Dart 3'). Then read with readAsStringSync() and print it with print.
Starter code
// Import the dart:io library
void main() {
// write to data.txt, read it and print
}Sample solution
import 'dart:io';
void main() {
var f = File('data.txt');
f.writeAsStringSync('Dart 3');
print(f.readAsStringSync());
}Expected output
Dart 3
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does readAsStringSync() return?
- A bool
- A Future
- An int
- A string (String) Correct answer
Explanation: readAsStringSync() returns a string.
2 The readAsStringSync call
var f = File('not.txt');
var content = f.____();
var f = File('not.txt');
var content = f.readAsStringSync();
Explanation: the file is read with readAsStringSync().
3 Reading parts
| Term | Meaning |
|---|---|
readAsStringSync() |
Sync reading |
readAsString() |
Async reading |
Future<String> |
Async return |
UTF-8 |
Encoding |