A reference to a directory (or folder) on the file system.
A Directory is an object holding a path on which operations can be performed. The path to the directory can be absolute or relative. It allows access to the parent directory, since it is a FileSystemEntity.
The Directory also provides static access to the system's temporary file directory, systemTemp, and the ability to access and change the current directory.
Create a new Directory to give access the directory with the specified path:
var myDir = Directory('myDir'); Most instance methods of Directory exist in both synchronous and asynchronous variants, for example, create and createSync. Unless you have a specific reason for using the synchronous version of a method, prefer the asynchronous version to avoid blocking your program.
The following code sample creates a directory using the create method. By setting the recursive parameter to true, you can create the named directory and all its necessary parent directories, if they do not already exist.
import 'dart:io';
void main() async {
// Creates dir/ and dir/subdir/.
var directory = await Directory('dir/subdir').create(recursive: true);
print(directory.path);
} Use the list or listSync methods to get the files and directories contained in a directory. Set recursive to true to recursively list all subdirectories. Set followLinks to true to follow symbolic links. The list method returns a Stream of FileSystemEntity objects. Listen on the stream to access each object as it is found:
import 'dart:io';
void main() async {
// Get the system temp directory.
var systemTempDir = Directory.systemTemp;
// List directory contents, recursing into sub-directories,
// but not following symbolic links.
await for (var entity in
systemTempDir.list(recursive: true, followLinks: false)) {
print(entity.path);
}
} I/O operations can block a program for some period of time while it waits for the operation to complete. To avoid this, all methods involving I/O have an asynchronous variant which returns a Future. This future completes when the I/O operation finishes. While the I/O operation is in progress, the Dart program is not blocked, and can perform other operations.
For example, the exists method, which determines whether the directory exists, returns a boolean value asynchronously using a Future.
import 'dart:io';
void main() async {
final myDir = Directory('dir');
var isThere = await myDir.exists();
print(isThere ? 'exists' : 'non-existent');
} In addition to exists, the stat, rename, and other methods are also asynchronous.
The Files and directories section of the library tour.
Write Command-Line Apps, a tutorial about writing command-line apps, includes information about files and directories.
FileSystemEntity. stat() function on path. stat() function on path.
© 2012 the Dart project authors
Licensed under the BSD 3-Clause "New" or "Revised" License.
https://api.dart.dev/stable/2.18.5/dart-io/Directory-class.html