How to load resource files or package: URIs in Dar

2019-04-10 07:43发布

问题:

There is a way to get the path of the currently executing script and then find the resource files relative to this location, but there is no guarantee that the directory structure is the same when the application is published.

Does Dart provide a generic way to load resources (files, data, ...) in a way that works also with pub run or pub global run?

Asked another way, how do I dynamically load the contents of a package: URI, in a Dart app, at runtime?

回答1:

Update The resource package was published.

Update This is being reworked. The Resource class will be moved to a package.

Original

There is a new Resource class in Dart (tested with Dart VM version: 1.12.0-edge.d4d89d6f12b44514336f1af748e466607bcd1453 (Fri Aug 7 19:38:14 2015))

resource_example/lib/resource/sample.txt

Sample text file.

resource_example/bin/main.dart

main() async {
  var resource = const Resource('package:resource_example/resource/sample.txt');
  print(await resource.readAsString());
  // or for binary resources
  // print(await resource.readAsBytes());
}

Executing

dart bin/main.dart

prints

Sample text file.

Executing

pub global activate -spath . 
pub global run resource_example:main

also prints

Sample text file.

It's also possible to pass the content of a variable as a resource. This might for example be convenient in unit tests to pass mock resources.

const sampleText = "Sample const text";

main() async {
  var uriEncoded = sampleText.replaceAll(' ', '%20');
  var resource = new Resource('data:application/dart;charset=utf-8,$uriEncoded');
  print(await resource.readAsString());
}

Arbitrary file or http uris are supported as well but this might not work when using pub run or pub global run when using relative paths.

main() async {
  var uri = new Uri.file('lib/resource/sample.txt');
  var resource = new Resource(uri.toString());
  print(await resource.readAsString());
}

For more details see
- http://blog.sethladd.com/2015/08/dynamically-load-package-contents-with.html
- https://codereview.chromium.org/1276263002/



标签: dart