Reading static files under a library in Dart?

可紊 提交于 2019-12-04 16:57:07
Kai Sellgren

As mentioned, you can use mirrors. Here's an example using what you wanted to achieve:

test.dart

import 'foo.dart';

void main() {
  print(Foo.getMyPath());
}

foo.dart

library asd;

import 'dart:mirrors';

class Foo {
  static Path getMyPath() => new Path('${currentMirrorSystem().libraries['asd'].url}/resources/');
}

It should output something like:

/Users/Kai/test/lib/resources/

There will probably be a better way to do this in a future release. I will update the answer when this is the case.

Update: You could also define a private method in the library:

/**
 * Returns the path to the root of this library.
 */
_getRootPath() {
  var pathString = new Path(currentMirrorSystem().libraries['LIBNAME'].url).directoryPath.toString().replaceFirst('file:///', '');
  return pathString;
}
John Evans

The dart mirrors API (still experimental, and not available on all platforms such as dart2js yet) exposes a url getter on the LibraryMirror. This should give you what you want.

I'm not aware of any other way to get this information on a library.

#import('dart:mirrors');
#import('package:mylib/mylib.dart'); 

main(){
   final urlOfLib = currentMirrorSystem().libraries['myLibraryName'].url;
}
Matt B

Generally the usual method of accessing resources which are located at a static position with your library is by use using a relative path.

#import('dart:io');

...

var filePath = new Path('resources/cool.txt');
var file = new File.fromPath(filePath);

// And if you really wanted, you can then get the full path
// Note: below is for example only. It is missing various
// integrity checks like error handling.
file.fullPath.then((path_str) {
  print(path_str);
});

See addition API information on Path and on File

As an aside.. If you absolutely wanted to get the same type of output as __FILE__ you can do something like the following:

#import('dart:io');
...
var opts = new Options();
var path = new Path(opts.script);
var file = new File.fromPath(path);
file.fullPath().then((path_str) {
  print(path_str);
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!