I want to know what the script's directory is. I have a command-line Dart script.
How to list the contents of a directory in Dart. final dir = Directory('path/to/directory'); final List<FileSystemEntity> entities = await dir. list(). toList();
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.
To list all the files or folders, you have to use flutter_file_manager, path, and path_provider_ex flutter package. Add the following lines in your pubspec. yaml file to add this package in your dependency. Add read / write permissions in your android/app/src/main/AndroidManifest.
If you're doing this for a console based app (e.g. in a unit test) and intend to use the output to open a file for reading or writing, it's more helpful to use Platform.script.path
:
import "package:path/path.dart" show dirname, join;
import 'dart:io' show Platform;
main() {
print(join(dirname(Platform.script.path), 'test_data_file.dat'));
}
The result of that command can be used with a File
object and be opened/read (e.g. if you have a unit test that needs to read/compare sample data, or a console program that needs to open a file relative to the current script for some other reason).
The easiest way to find the script's directory is to use the path package.
import "package:path/path.dart" show dirname;
import 'dart:io' show Platform;
main() {
print(dirname(Platform.script.toString()));
}
Put the path package into your pubspec.yaml:
dependencies:
path: any
And be sure to run pub get
to download and link the path package.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With