John Evans
John Evans

Reputation: 7393

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

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.

Upvotes: 10

Views: 4077

Answers (2)

TSR
TSR

Reputation: 20590

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
}

Upvotes: 0

SBNTT
SBNTT

Reputation: 186

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

Upvotes: 11

Related Questions