一个适用于所有平台的单例隔离工作进程。在大多数平台上,它使用 Flutter 的 Isolate,除了 Web 平台,因为 Isolate 不可用,它使用 Worker 代替。

功能

  • ? 易于使用*
  • ? 语法与 Flutter 提供的 compute 函数相同*
  • ? 不是一次性的工作进程
  • ? Web 平台可用**

*Web 平台除外
**通过使用 JsIsolatedWorker

用法

基本示例

int doSomeHeavyCalculation(int count) {
    // ...
}
void main() {
    // if using compute function:
    // compute(doSomeHeavyCalculation, 1000);
    IsolatedWorker().run(doSomeHeavyCalculation, 1000);
}

如果我们想执行一些不需要任何参数和/或返回值就能完成的繁重工作。

// WRONG
void doSomethingHeavy() {
    // ...
}

// CORRECT
void doSomethingHeavy(void _) {
    // ...
}

void main() {
    IsolatedWorker().run(doSomethingHeavy, null);
}

Web 示例

我们可以利用 JsIsolatedWorker 来启动一个 Web Worker。然而,由于一些限制,它不能使用 Dart 闭包作为消息传递给 Worker(我尝试过使用 JSONfnallowInterop,但都没有成功)。
相反,我们需要使用原生的 JS 闭包。要做到这一点,我们可以利用现有的 JS API 或通过导入外部库/文件。

假设我们要使用 JSON.stringify 来字符串化对象。

void main() {
    JsIsolatedWorker().run(
        functionName: ['JSON', 'stringify'],
        arguments: {},
        // optional argument, in case web worker is not available.
        fallback: () {
            return '{}';
        },
    ).then(print);
    // prints "{}"
}

现在假设我们有想要 Worker 使用的外部 JS 库/文件。

void main() async {
    // import the scripts first
    // and check if web worker is available
    final bool loaded = await JsIsolatedWorker().importScripts(['myModule1.js']);
    // web worker is available
    if(loaded) {
        print(await JsIsolatedWorker().run(
            functionName: 'myFunction1',
            arguments: 'Hello from Dart :)',
        ));
    }else{
        print('Web worker is not available :(');
    }
}

Web Worker 设置

为了让 JsIsolatedWorker 在 Flutter Web 上正常运行,需要在 web 文件夹中有一个单独的 worker.js 文件。你可以 在此处 下载它,并将其放在你的 web 文件夹中,如下所示

...
web /
    index.html
    worker.js
    ...

示例

  • Fetch – 一个使用 IsolatedWorkerJsIsolatedWorker 从 URL 获取响应的示例

GitHub

https://github.com/iandis/isolated_worker