Dart: Using JsObject and window API in an isolate

Issue

I am having some difficulties making use of isolates in Dart. The first problem is I wanted to use dart:js to use a javascript library in one of my isolates. I tried with the following code:

void runCode(SendPort sendPort)
{
    print("still ok...");
    JsObject object = new JsObject(context['jsCode']);
    print("still ok?");
}

void main()
{
    ReceivePort receivePort = new ReceivePort();
    JsObject object = new JsObject(context['jsCode']);
    print("ok so far");
    Isolate.spawn(runCode, receivePort.sendPort);
}

The code runs as far as “still ok…” in the runCode function and breaks when I try to use JsObject.

The second problem was I wanted to use the fileSystem API in the isolate. So I tried the following:

void runCode(SendPort sendPort)
{
    window.requestFileSystem.then((FileSystem filesytem) => print('ok'));
}

void main()
{
    ReceivePort receivePort = new ReceivePort();
    Isolate.spawn(runCode, receivePort.sendPort);
}

This second example breaks when I reach the filesystem.

I have read: Dart : Isolate not working when using html import and from here it suggests that dart:html cannot be used in an isolate. Is this the reason why the filesystem API will not work? Is this the same case for dart:js? Or am I completely missing something?

Thanks for any help!

Solution

I’ve read somewhere that only the main thread has access to the DOM, which would cause any other JS action to fail if not in the main thread.

Answered By – Randal Schwartz

Answer Checked By – Pedro (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.