4

I'm trying to make an app in flutter, iOS+Android+Web but a few. plugins don't offer web support.

I found npm packages of the same sdk and want to use

flutter iOS+Android with iOS+android plugin sdk. flutter web + npm package sdk.

Is there a way to use npm/node packages in a flutter web app if the plugins don't have web support?

ir2pid
  • 5,604
  • 12
  • 63
  • 107

1 Answers1

2

Try using webpack.

In one of my projects I had to call Javascript (since isolates on web don't work as expected). I created a separate project with javascript, and had webpack script compile directly into flutter web folder. Granted, I didn't use any npm packages, but I don't see why it should not work.

This is my webpack.config.js (/src/worker.js is the entry javascript file):

const CopyWebpackPlugin = require('copy-webpack-plugin');
const webpack = require('webpack');
const path = require('path');

module.exports = {
    mode: 'production',
    entry: './src/worker.js',
    output: {
        filename: '[name].bundle.js',
        path: path.resolve(__dirname, '../flutter_app/web/', 'my_js')
    }
}

In your Dart code you can use Worker class to call the script, something like:

var myWorker = Worker('../my_js/main.bundle.js');
    myWorker.onMessage.listen((returnValue) {
//Some processing here...
});
var event = {"arg1": "value1", "arg2": "value2"};
myWorker.postMessage(json.encode(event));

** Update: this is what the worker ('./src/worker.js') receiving the call looked like:

import algorithm from './index'; 

onmessage = async function(messageEvent) {

  let event=JSON.parse(messageEvent.data);
  let message=await algorithm (event);
  postMessage(message);

}
Andrija
  • 1,534
  • 3
  • 10
  • I have same requirement, but can you explain this worker class and what did you do? – Pooja Aggarwal Aug 11 '21 at 07:57
  • I updated my answer with the worker entry code. I was developing a game app, and I had algorithm that run for 2 seconds to get the next move. On Android the isolates worked just fine, but on web it run in the same thread, which blocked the main thread. This worker configuration was working fine. I'm not sure if the Isolates in flutter web work fine now - if they do, you could just work with regular isolates. – Andrija Aug 15 '21 at 13:20