Directory
- Dart course
- Intermediate
- Lesson 92/116
- 5 min
Learn folder operations with Directory.
Folders with Directory
Directory represents a folder. With Directory('data') you create a folder object. createSync(recursive: true) creates the folder and, if needed, its parents.
listSync() lists the files and subfolders in the folder. Each item is a FileSystemEntity; you read its path with .path.
Directory also has existsSync() and deleteSync() methods; it works like File.
Listing folder contents
Directory.listSync() gives the folder's contents as a list. Each item is a FileSystemEntity; its .path property gives the path.
Example: for (var e in d.listSync()) { print(e.path); }. This prints the path of every file and subfolder.
The list order can vary by operating system; do not rely on it. If you only want existence, use existsSync().
Practice Folder and file
Import the library with import 'dart:io';. In main create Directory('notes') and create it with createSync(recursive: true). Create File('notes/a.txt'), write with writeAsStringSync('hello'), then read with readAsStringSync() and print it with print.
Starter code
// Import the dart:io library
void main() {
// create the notes folder, write a.txt inside, read and print
}Sample solution
import 'dart:io';
void main() {
Directory('notes').createSync(recursive: true);
var f = File('notes/a.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 The createSync call
var d = Directory('data');
d.____(recursive: true);
var d = Directory('data');
d.createSync(recursive: true);
Explanation: the folder is created with createSync.
2 What does Directory.listSync() return?
- A string
- An int
- A list of FileSystemEntity Correct answer
- A bool
Explanation: listSync() returns a list of FileSystemEntity.
3 Directory parts
| Term | Meaning |
|---|---|
Directory('data') |
Folder object |
createSync() |
Creation |
listSync() |
Listing |
FileSystemEntity |
List item |