Get script path in Dart (analog __DIR__ constant i

2020-02-07 05:06发布

问题:

How I can get path of the current script (not executable) in Dart?

For example. In PHP we have __DIR__ constant, that reffer to script directory. If we have two scripts: ./run.php and ./lib/test.php; and in ./run.php we just include ./lib/test.php. Code in ./lib/test.php output __DIR__. if we run ./run.php then we get in output /path/to/lib/test.php.

In Dart we can get directory of the current run script, but how I can get directory of the current script?

I need in this, because I'm try to get json-file (that placed in library) from the library.

How I can do this?

回答1:

You've said that when you run test.dart, the current directory is /path/to/lib/tests. So you should be able to use a relative path to open rules.json. The path is ../rules/rules.json (or of course, ..\rules\rules.json on Windows, you can get the separator from Platform.pathSeparator).

Alternately, apparently you can get a Uri for the current script (if supported by the platform) from Platform.script.



回答2:

When you want to reference a file in the lib directory you use a package-relative path.

packages/my_package/lib/rules/rules.json

When the file from where you want to reference to another file is not in one of the top-level directories like web, example, bin, test, ... you have to navigate to the top before going down through the packages directory.
This way works within every file to every target file inside the lib directory of the current app package or any package you have declared as dependency in pubspec.yaml.

  ../packages/my_package/lib/rules/rules.json

pub build gives hints when you are not navigating up enough.

Example

the file containing main is in playground/bin/script/script_path/main.dart
the test.json file is in playground/lib/some_json

import 'dart:io' as io;

main() {
  Uri filePath = io.Platform.script.resolve(
      '../../../packages/playground/some_json/test.json');
  var file = new io.File.fromUri(filePath);
  var content = file.readAsString().then((c) {
    print(c);
  });
}

On the server you don't need to navigate up (at least currently) because each directory has a symlink to the packages directory, but there are plans to get rid of symlinks and dart2dart probably works like dart2js and may make it necessary to navigate up first like in browser apps.



回答3:

If you are in a flutter project and trying to load static assets eg. json, txt, images: Use rootBundle as mentioned in https://flutter.dev/docs/development/ui/assets-and-images#loading-text-assets

import 'dart:async' show Future;
import 'package:flutter/services.dart' show rootBundle;

Future<String> loadAsset() async {
  return await rootBundle.loadString('assets/config.json');
}

Also make sure you add that file in pubspec.yaml

flutter:
  assets:
    - assets/config.json


标签: dart