Does Flutter Web's "compute()" work on it's own thread or web worker, or how does it work?
Asked Answered
S

2

9

If I do this, for example:

FutureBuilder(
   initialData: null,
   future: compute(expensiveParsingOperation, data),
   builder: (context, snapshot) {
       if(!snapshot.hasData){
          // This doesn't spin (frozen).  The entire UI is janked until the expensive operation future completes.
          CircularProgressIndicator(); 
        }else {  
             Container(); 
         } 
});

I expected the above to send expensiveParsingOperation function to a web worker or something and not jank the main thread, but this is not what is occurring in my observation.

Sawyor answered 13/1, 2020 at 7:7 Comment(1)
I found a small Dart library that will help you to use Web Workers in Dart as Isolate integration on web has been discontinued with Dart 2. Check out github.com/deakjahn/flutter_isolate_webMichail
E
11

compute does nothing on the web platform at this time see https://github.com/flutter/flutter/issues/33577

Euraeurasia answered 27/1, 2020 at 16:11 Comment(1)
Is there any alternative or workaround of compute on web ?Moraine
M
0

To give more context why it is not working on web, https://github.com/flutter/flutter/issues/33577

The approach to do this is to write a standalone dart file and compile it to Javascript. That's extra compile step is the reason why this is not natively supported in Dart. For example, here is your standalone script:

import 'package:js/js.dart';


@JS('myworker')
external set myworker(obj);
void main() {
  myworker = allowInterop((args) {
    // do your work here
  });
}

You have to compile it JS. Assuming this file is lib/myworker.dart, compile with: dart compile js -O2 -o web/myworker.js lib/myworker.dart

You would call it in your dart/flutter app like this:

final loaded = await JsIsolatedWorker().importScripts(['myworker.js']);
if (loaded) {
  final result = await JsIsolatedWorker().run(
    functionName: 'myworker',
    arguments: 'my args',
  );
  // use the result
}
Moraine answered 11/4 at 21:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.