Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the directory of the current script, in Dart?

Tags:

dart

dart-io

I want to know what the script's directory is. I have a command-line Dart script.

like image 935
Seth Ladd Avatar asked Oct 27 '13 20:10

Seth Ladd


People also ask

How do I get all the files in a directory Dart?

How to list the contents of a directory in Dart. final dir = Directory('path/to/directory'); final List<FileSystemEntity> entities = await dir. list(). toList();

What is directory in Dart?

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.

How do I read a directory in flutter?

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.


2 Answers

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).

like image 152
Dan Field Avatar answered Oct 26 '22 11:10

Dan Field


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.

like image 36
Seth Ladd Avatar answered Oct 26 '22 11:10

Seth Ladd