Get script path in Dart (analog __DIR__ constant in PHP)

后端 未结 3 1172
眼角桃花
眼角桃花 2020-12-12 00:57

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

相关标签:
3条回答
  • 2020-12-12 01:19

    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.

    0 讨论(0)
  • 2020-12-12 01:20

    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.

    0 讨论(0)
  • 2020-12-12 01:26

    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
    
    0 讨论(0)
提交回复
热议问题