Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Web Workers handling in wasm build. #327

Open
ebala96 opened this issue Dec 17, 2024 · 1 comment
Open

Web Workers handling in wasm build. #327

ebala96 opened this issue Dec 17, 2024 · 1 comment
Labels
type-question A question about expected behavior or functionality

Comments

@ebala96
Copy link

ebala96 commented Dec 17, 2024

I have a web worker code piece in my project.
It works fine when I do a flutter run web or take a web build.

But when I try to do a flutter run web --wasm or flutter build web --wasm, the web worker part does not work.
I am not able to do postMessage to my web worker instance.

Code snippet for creating and sending messages to web worker:

import 'dart:async';
import 'dart:js_interop';
import 'dart:typed_data';
import 'package:web/web.dart' as web;

class WebWorkers {

  final _workers = <int, web.Worker>{};

  Future<int> create(String url) async{
    print('WebWorkersWeb.create: $url');
    final worker = web.Worker(url.toJS);
    final id = _workers.length;
    _workers[id] = worker;
    return id;
  }
  
   Stream<String> onMessage(int id) {
      print('WebWorkersWeb.onMessage: $id');
      final worker = _workers[id];
  
      if (worker == null) {
        throw PlatformException(
          code: 'Unimplemented',
          details: 'web_worker for web doesn\'t implement \'${id}\'',
        );
      }
  
      final controller = StreamController<String>();
      worker.addEventListener('message', (web.MessageEvent msg){
        print('message from worker is ${msg.data.toString()}');
        controller.add(msg.data.toString());
      }.toJS);
  
      return controller.stream;
   }
    
   Future<void> postMessage(int id, String message) async{
      print('WebWorkersWeb.postMessage: $id, $message');
      final worker = _workers[id];
  
      worker.postMessage(message.toJS);
   }

}

Does web worker in wasm builds require any additional handling?

@srujzs srujzs added the type-question A question about expected behavior or functionality label Dec 18, 2024
@srujzs
Copy link
Contributor

srujzs commented Dec 18, 2024

Can you share a minimal repro and the error you are seeing here? The above example doesn't have a main method. There shouldn't be any additional handling for web workers when compiling to Wasm.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
type-question A question about expected behavior or functionality
Projects
None yet
Development

No branches or pull requests

2 participants