Flutter/Dart: Simplifying Isolate and Worker Usage

·

1 min read

By using the isolate_manager v5.0.0, the Isolate on the VM and Worker on the Web will be implemented more easily than ever.

This package uses js_interop and the web package under the hood, so the app can freely compile to WASM.

Firstly, add an annotation to a function that you want to use as a Worker:

@isolateManagerWorker
int add(List<int> params){
  return params[0] + params[1]
}

@isolateManagerWorker
int subtract(List<int> params) {
  return params[0] - params[1];
}

Note that those functions can not be depended on any Flutter UI library like dart:ui or dart:io which are not supported when compiling to js.

Then create an IsolateManager instance:

final isolatedAdd = IsolateManager.create(
                      add, 
                      workerName: 'add', 
                      concurrent: 2,
                   );

final isolatedSubtract = IsolateManager.create(
                      subtract, 
                      workerName: 'subtract', 
                      concurrent: 2,
                   );

Run this command to generate the Workers:

dart run isolate_manager:generate

Now we can use it to compute something like:

final addResult = await isolatedAdd([50, 30]); // 80
final subtractResult = await isolatedSubtract([50, 30]); //20

Or

StreamBuilder(
  stream: isolatedAdd.stream,
  builder: (context, snapshot) {
    if (!snapshot.hasData) {
      return const Center(
        child: CircularProgressIndicator(),
      );
    }
    return Text('Isolated Add: ${snapshot.data}');
  },
),

That’s it. Those isolated functions will work on both VM (via Isolate) and Web (via Worker).

Thank you for your reading.