dart:io
- Dart course
- Intermediate
- Lesson 88/116
- 5 min
Learn file operations with dart:io.
The dart:io library
The dart:io library provides file, directory and process operations. It is imported with import 'dart:io';. The File class represents files, the Directory class represents folders.
For example File('note.txt') creates a file object. You write to it with writeAsStringSync('Hello') and read it with readAsStringSync().
Note: dart:io does not work on the web platform. It is used in CLI and server apps; on Flutter mobile it is also limited.
File and Directory
File represents a file, Directory a folder. Both come from dart:io. File('a.txt') denotes a file, Directory('data') a folder.
Both have existsSync() for existence and createSync() for creation. Write/read methods are on File, listing on Directory.
Paths use the slash /; for cross-platform paths Dart recommends the path package.
Practice Write and read a file
Import the library with import 'dart:io';. In main create File('note.txt'); write with writeAsStringSync('Hello'). Then read with readAsStringSync() and print it with print.
Starter code
// Import the dart:io library
void main() {
// write to not.txt, read it and print
}Sample solution
import 'dart:io';
void main() {
var f = File('note.txt');
f.writeAsStringSync('Hello');
print(f.readAsStringSync());
}Expected output
Hello
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Importing dart:io
import '____';
void main() {}
import 'dart:io';
void main() {}
Explanation: dart:io is imported for file operations.
2 Which classes does dart:io provide?
- Widget and BuildContext
- List and Set
- File and Directory Correct answer
- Future and Stream
Explanation: dart:io provides the File and Directory classes.
3 dart:io parts
| Term | Meaning |
|---|---|
File('a.txt') |
File |
Directory('data') |
Folder |
existsSync() |
Existence check |
readAsStringSync() |
Reading |