Web Worker and Dart #1

Update 17 Dec 2018: I figured a better way to do Web Worker in Dart and created the second part of this story, do check it out here.

By the time I found Dart and AngularDart, isolate support in web already been deprecated. Googling around the internet and found only traces of its discontinuing and unanswered questions of web worker + dart web.

But I need it. And I really hate to see idle CPUs. So here’s what I did…

Start a web worker from main.dart

dart.html provided a Worker class, and it works beautifully. This part is a no-brainer.

This is similar to how you will operate with a Worker in JavaScript. Instead of sending out String to worker (which works), I opt to use custom object which is more likely the common use case.

Write a web worker with dart

As much as I thought it will be a complex solution, and I spent a few hours to distill it to the final version, it turns out to be a straight forward one. Guess I am pretty dumb in this.

Notice that I didn’t import dart.html here. We shouldn’t, because that library is sort of tailor to a situation provided a valid window object.

Passing around custom object

lib/dog package is shared between master and worker. worker.dart is able to directly cast the passed in object into the Dog class. The caveat is, when I pass this object back to main.dart via postMessage(), master cannot do the same implicit cast. MessageEvent.data became a Map<String, dynamic> there. This is caveat #1.

We need to make use of package:js interoperability to make Dog object passable between master and worker.

Running the web app

main.dart and worker.dart both need to reside in the web/ folder. They share the same custom package of dog, which lived in the lib/ folder.

Now, the major caveat: to run this web app with web worker correctly in the browser during development, instead of the common webdev serve, we need to use webdev serve -r. Which indicate a release version, in other word, use dart2js instead of dartdevc. This hinder debugging by lot. Caveat #2.


I’m new to dart, and all its relatives. This post is meant to share my adventure rather than provide a correct example of how to do this. Please comment or put up issue in the github repro if you think there is thing to improve or corrected. Especially solution or better workaround for the caveats.

Github repro is here: https://github.com/yuan-kuan/dog-raiser

I drew a great deal of ideas from https://github.com/isoos/service_worker.


Kota Kinabalu, Malaysia
Email me

Usually types codes. A decade in games development, now trying to learn web.