An isolated worker for Flutter (Isolate) and Web (Web Worker). Behaves almost the same as the compute function, except it is not a one-off worker.

Overview

A singleton isolated worker for all platforms. On most platforms, it uses Flutter's Isolate, except on the web, since Isolate is not available, it uses Worker instead.

Features

  • 💙 Easy to use*
  • 👬 Identical syntax to the compute function provided by Flutter*
  • 🚫 Not a one-off worker
  • 🌐 Available on web**

*except on web **by using JsIsolatedWorker

Usage

Basic example

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

If we want to do some heavy work that does not need any arguments and/or return values.

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

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

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

Web example

We can utilize the JsIsolatedWorker for spawning a web worker. However, it cannot use Dart closures as messages to the worker because of some limitations (I have tried using JSONfn and allowInterop but no luck). Instead we need to use native JS closures. In order to do this, we can utilize existing JS APIs or by importing external libraries/files.

Let's assume we want to stringify objects using JSON.stringify.

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

Now let's assume we have external js libraries/files that we want the worker to use.

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 Setup

In order for JsIsolatedWorker to run properly on Flutter web, there needs to be a single worker.js file in the web folder. You can download it here and put it in your web folder like below

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

Examples

  • Fetch - an example of how to get response from a URL using IsolatedWorker and JsIsolatedWorker
Comments
  • LateInitializationError: Field '_isolate@965339056' has not been initialized.

    LateInitializationError: Field '_isolate@965339056' has not been initialized.

    When running the isolate for the first time it fails. Then all isolates afterwards succeed.

    Looks like a library bug.

    
    flutter: LateInitializationError: Field '_isolate@965339056' has not been initialized.
    [ERROR:flutter[/lib/ui/ui_dart_state.cc]()(209)] Unhandled Exception: LateInitializationError: Field '_isolate@965339056' has not been initialized.
    #0      IsolatedWorkerImpl._isolate (package:isolated_worker[/src/isolated_worker_default_impl.dart]())
    package:isolated_worker/src/isolated_worker_default_impl.dart:1
    #1      IsolatedWorkerImpl.close
    package:isolated_worker/src/isolated_worker_default_impl.dart:181
    #2      _compressImageInBackground
    package:bap/…/files/compress_image.dart:156
    #3      _Worker._runCallback
    package:isolated_worker/src/isolated_worker_default_impl.dart:221
    #4      _Worker._parentMessageReceiver
    package:isolated_worker/src/isolated_worker_default_impl.dart:212 
    
    bug good first issue 
    opened by ollydixon 6
  • Usage on web

    Usage on web

    Hi, I am currently getting the following error:

    UnimplementedError: structured clone of other type
    

    I am calling the JsIsolatedWorker like this:

    cropped = Uint8List.fromList(await JsIsolatedWorker().run(
            functionName: 'cropImageDataWithDartLibrary',
            arguments: editorKey.currentState!
    )
    

    and this is the function I am trying to run in the worker:

    Future<Uint8List?> cropImageDataWithDartLibrary(
          ExtendedImageEditorState state) async {
        print('dart library start cropping');
    
        ///crop rect base on raw image
        final Rect? cropRect = state.getCropRect();
    
        print('getCropRect : $cropRect');
    
        final Uint8List data = state.rawImageData;
    
        final EditActionDetails editAction = state.editAction!;
    
        final DateTime time1 = DateTime.now();
    
        img.Image? src = await compute(img.decodeImage, data);
    
        List<int>? fileData;
        if(src != null){
          final DateTime time2 = DateTime.now();
          //clear orientation
          src = img.bakeOrientation(src);
    
          if (editAction.needCrop) {
            src = img.copyCrop(src, cropRect!.left.toInt(), cropRect.top.toInt(),
                cropRect.width.toInt(), cropRect.height.toInt());
          }
    
          if (editAction.needFlip) {
            late img.Flip mode;
            if (editAction.flipY && editAction.flipX) {
              mode = img.Flip.both;
            } else if (editAction.flipY) {
              mode = img.Flip.horizontal;
            } else if (editAction.flipX) {
              mode = img.Flip.vertical;
            }
            src = img.flip(src, mode);
          }
    
          if (editAction.hasRotateAngle) {
            src = img.copyRotate(src, editAction.rotateAngle);
          }
          final DateTime time3 = DateTime.now();
          print('${time3.difference(time2)} : crop/flip/rotate');
    
          print('start encode');
          final DateTime time4 = DateTime.now();
    
          fileData = await compute(img.encodeJpg, src);
    
          final DateTime time5 = DateTime.now();
          print('${time5.difference(time4)} : encode');
          print('${time5.difference(time1)} : total time');
        }
        return Uint8List.fromList(fileData!);
      }
    

    I probably didn't understand how this package is supposed to be used on web; could you point me in the right direction?

    opened by SeriousMonk 5
  • DB operation using moor within JsIsolatedWorker

    DB operation using moor within JsIsolatedWorker

    Hi, i am using moor for DB in my application, is it possible to use moor DB connection within JsIsolatedWorker, any alternate ways to establish DB connection in JsIsolatedWorker.

    opened by KiraKmp 4
  • Import modules into fetch_function.js file

    Import modules into fetch_function.js file

    I have the scripts working the way you have shown. Thank you.

    I'm trying to take it a step further in using js packages, specifically node-jsencrypt. This is probably a JS question, and I am just unfamiliar with the JS specifics.

    How can I load the JS Encrypt package to use with this?

    In my dart file to trigger the JSIsolated Worked:

    bool _areScriptsImported = false;
      static const List<String> _jsScripts = <String>[
        'fetch_function.js',
      ];
    
    Future<String> jsIsolateDecrypt(String message) async {
        if (!_areScriptsImported) {
          await JsIsolatedWorker().importScripts(_jsScripts);
          _areScriptsImported = true;
        }
        String decrypted = await JsIsolatedWorker().run(
          functionName: 'getDecrypt',
          arguments: message,
        ) as String;
        return decrypted;
      }
    

    Inside the fetch_function.js file:

    const JSEncrypt = require('node-jsencrypt')
    
    function getDecrypt(encrypted) {
      var crypt = new JSEncrypt();
      crypt.setPrivateKey(privateKey);
      return crypt.decrypt(encrypted);
    }
    
    

    I get this error:

    Error: ReferenceError: Cannot access 'JSEncrypt' before initialization

    Any ideas? Thank you.

    opened by jonnyjohnson1 3
  • Hello, can u help!?)

    Hello, can u help!?)

    Thanks for the written package. Could you please provide more examples for the flutter WEB on how to work correctly with this API? just simple examples)

    documentation 
    opened by NickKoroloff 3
  • document is not supporting inside JS function which called by isolate_worker

    document is not supporting inside JS function which called by isolate_worker

    I am creating the element using the document.createElement('input') inside the JS function. I am calling that function using the JsIsolatedWorker().run(functionName: 'alertMessage',arguments: '100') It is giving me error:

    This is my JS function. I am getting image using input type=file. Plan is to return file path from this function.

    async function createDynamicInput() {
    var input = document.createElement('input');
    input.type = 'file';
    input.onchange = e => {
       var file = e.taralertMessageget.files[0];
       console.log(file);
       return file;
    }
    input.click();
    }
    

    Calling this function using:

    var result = await JsIsolatedWorker().run(
            functionName: 'createDynamicInput',
            arguments: '100',
          );
          print("==$result");
    
    

    Error: ReferenceError: document is not defined.

    Let me know the correct way or require to make changes into current code. Thanks

    opened by deepbhavsar 2
  • Bidirectional Communication with worker

    Bidirectional Communication with worker

    Hello, Is it possible to have bidirectional communication with the worker . I want to use isolate for Firebase Query listener, it needs to reply back the messages and also I need to shut down the listener or change its parameter on go

    regard

    opened by yashhema 1
  • fix(isolated-worker-default): fix late init error on close

    fix(isolated-worker-default): fix late init error on close

    This fixes #13

    The error occurs on IsolatedWorkerImpl.close because the Isolate was not given a chance to warm up, making it throw LateInitializationError (because the Isolate object hasn't been created). This PR fixes it by awaiting the main SendPort to receive the child SendPort first so that the Isolate object can be created thus can be closed.

    opened by iandis 0
  • `🚀feat(worker-delegator)`: new WorkerDelegator

    `🚀feat(worker-delegator)`: new WorkerDelegator

    New WorkerDelegator works as a bridge between IsolatedWorker and JsIsolatedWorker. Hopefully with this new feature, user can use both IsolatedWorker and JsIsolatedWorker easier and cleaner.

    enhancement 
    opened by iandis 0
Owner
Iandi Santulus
a senior cs student who loves building apps using Flutter
Iandi Santulus
Flutter's compute function made available for all non-Flutter Dart programs

compute Flutter's compute function made available for all non-Flutter Dart programs The compute package takes Flutter's compute function and makes it

dartside.dev 6 Nov 10, 2022
Off-road-inclinometer - A Flutter app to monitor pitch and roll when off roading

Off-Road Inclinometer A Flutter app to monitor pitch and roll when off roading.

Samuel Huff 1 Feb 26, 2022
A simple detailed flutter widget that looks almost the same as the real instagram mention widget.

Instagram Mention Widgets 'small details do matter' ❤️ This package provides simple and almost the same UI details that the real Instagram mention wid

AbdulMuaz Aqeel 20 Oct 10, 2022
Cross-platform flutter plugin for reading and writing NFC tags. Not maintained anymore - not looking for new maintainer, fork instead.

nfc_in_flutter NFC in Flutter is a plugin for reading and writing NFC tags in Flutter. It works on both Android and iOS with a simple stream interface

Andi Semler 113 Sep 28, 2022
GitHub Action that uses the Dart Package Analyzer to compute the Pub score of Dart/Flutter packages

Dart/Flutter package analyzer This action uses the pana (Package ANAlysis) package to compute the score that your Dart or Flutter package will have on

Axel Ogereau-Peltier 45 Dec 29, 2022
App de teste que executa uma função de fibonacci em background utilizando compute.

app_isolate_compute A new Flutter project. Getting Started This project is a starting point for a Flutter application. A few resources to get you star

Isaque Santos Paixão 0 Jan 7, 2022
Isolate helper for flutter and dart.

Isolation Overview The package simplifies the creation and interaction between isolates. It encapsulates the entire boilerplate, leaving the developer

Plague Fox 15 Oct 29, 2022
Learn how to build a multi-step form flow and how to use bloc to effectively isolate the presentation layer from the business logic layer.

Multi-page Form Flow Learn how to build a multi-step form flow and how to use bloc to effectively isolate the presentation layer from the business log

Sandip Pramanik 15 Dec 19, 2022
Dart package that conveniently wraps an isolate, ports and state for easy isolates.

Isolate Agents Description Isolate Agents adds a new class, Agent, which is a proper implementation of the Actor model for Dart. Where Isolates have n

null 65 Jan 2, 2023
Flutter form fields designed to take much of the burden of form-related coding off the programmer's back — masks, validations, keyboard type, etc.

well_formed Contents Overview Getting Started Demo application References Overview Well-Formed Widget Fields - Well-Formed - is a collection of Flutte

Dartoos 7 Nov 2, 2022
A new Flutter package customtoggleswitch is used to toggle a setting between on/off which is true/false respectively Created by suryadevsingh.

CustomToggleSwitch A new Flutter package customtoggleswitch is used to toggle a setting between on/off which is true/false respectively Created by sur

Surya Dev Singh 1 Jun 9, 2020
Flutter control system widgets, like on-off controller.

control_system Flutter control system widgets, like on-off controller. Introduction A control system manages, commands, directs, or regulates the beha

Amirreza Madani 0 Jan 9, 2022
A Flutter package which allows you to work with MethodChannels in Isolate.

A Flutter package which allows you to work with MethodChannels in Isolate. Also it provides simplified multiplatform Isolate API.

Zemlaynikin Max 19 Jan 4, 2023
Aplicativo de teste que roda em background timer atual utilizando Isolate.

# isolate_app A new Flutter project. ## Getting Started This project is a starting point for a Flutter application. A few resources to get you sta

Isaque Santos Paixão 1 Jun 20, 2022
This a library to simplify isolate thread communication.

This a library to simplify islate thread communication. It abstracts the data transfer between islate and the main thread into a simple channel, and t

吴楚衡 3 Oct 31, 2022
CRUD Table Flutter consists of a Lazy loading function, resizable columns, and integrated CRUD Form.

CRUD Table Flutter CRUD Table Flutter is a package for crating CURD-UI for your entity/object/class easily. It consists of a Lazy loading function, re

null 10 Dec 31, 2022
Flutter-sorted-chips-row - Flutter library for rendering a row of Material "Chip" buttons that gets sorted according to the given function

sorted_chips_row A Flutter Widget displaying a row of Material Chips, sorted according to the provided comparison function. How to use Adding dependen

Callstack Incubator 29 Jul 29, 2021
FlutterAgoraFirebaseVideoCall (Agora RTC, Bloc Pattern, Cubit, Firestore, Cloud Function, FCM)

Flutter Agora Fully Functional Video Call module Tech Stack Client: Dart, Flutter Server: Firebase firestore, Google cloud functions Techniques: *BloC

Youssef Elshiaty 39 Dec 16, 2022