Dart: how to specify an Isolate URI in an imported package?

Issue

I have written some code and I want to provide it in a package, but I want to also expose it to package consumers as a worker. For this purpose I have created a wrapper class, that runs an isolate internally and using the send command and listeners communicate with the Isolate to provide the functionality.

The problem arises when I want to use this wrapper class from bin or web directory: the Uri provided is interpolated from the directory of the running/main Isolate instead of from the package root. For bin it is packagename|bin/ and for web it is packagename|web.

I would like to export this class to the consumers so they can chose an easier approach than to construct their own Isolate, but I am not sure how to specify the main file that will be used in spawnUri.

Is there a way to specify the file so it will always be resolved to the correct file regardless of where the main Isolate is run from.

Structure:

// Exports the next file so the class in it will be package visible 
packageroot -> lib/package_exports_code_that_spawns_isolate.dart
// This file should contain URI that always resolve to the next file
packageroot -> lib/code_that_spawns_isolate.dart 
// The main worker/Isolate file
packageroot -> lib/src/worker/worker.dart

Thanks.

Solution

To refer to a library in your package, you should use a package: URI.
Something like:

var workerUri = Uri.parse("package:myPackage/src/worker/worker.dart");
var isolate = await Isolate.spawnUri(workerUri,...);

It’s not perfect because it requires you to hard-wire your package name into the code, but I believe it’s the best option currently available.

The Isolate.spawnUri function doesn’t (and can’t) resolve a relative URI reference wrt. the source file that called it – nothing in the Dart libraries depends on where it’s called from, that’s simply too fragile – so a relative URI isn’t going to work. The only absolute URI referencing your worker is a package: URI, so that’s what you have to use.

Answered By – lrn

Answer Checked By – Mildred Charles (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *