Is there a way to determine the directory of the file in which the Dart file is being executed?

Viewed 142

I'm writing a dart package in which I require the path to a file within the package to access the file for the package to work. The package is not written for the web platform. My understanding of where packages are stored is limited, however, I would assume that there won't be a common directory for each platform, and even within platforms, I suppose it would vary based on how dart was installed on the specific machine.

Despite this being rather obvious that Dart as an AOT language would mean that the file being executed is just one snapshot. I would want to know if there is a way I can access the directory structure of package without having the end-user having to pass path values to me.

To give you some context, I want to load a dynamic library on runtime using dart:ffi, and do so within a package which will be published to pub.dev with the libraries. Do let me know if you have any ideas.

What I've tried so far:

  • Directory.current.path: This is obviously not going to work.

  • ${File(Platform.resolvedExecutable).parent.path: This seems to be a workaround for Windows machines, I don't know how this would be useful for Linux, MacOS, or even Android and iOS for that matter.

  • Directory.fromUri(Platform.script) : This leads me to the snapshot created by the compiler on Linux, nevertheless, of no use to me.

1 Answers

It definitely won't work with ahead-of-time compilation, because then the compiled code is nowhere near the source code.

If your program is being run on the stand-alone VM, and has direct access to the source code, you can potentially use Isolate.resolvePackageUri from dart:isolate to convert a known package: URI to a file:URI, which can then be used withdart:io` to load the file.

Future<File?> fileFromPackageUri(Uri packageUri) async {
  var fileUri = await Isolate.resolvePackageUri(packageUri);
  if (fileUri == null) return null; // No such pacakge.
  return File.fromUri(fileUri);
}

Again, this only works when running from source. Otherwise you need to find a way to deploy your native library along with the Dart program and know where to find it.

Related