Flutter Web JS to Dart

Guys, please help me, I’ve been struggling for a few days now. I used js.dart and js_interop and I can’t get data from js on the flutter side in any way. (me need to call the flutter method with js)
:man_facepalming:

Flutter

@JS('window.sendToFlutter')
external set sendToFlutter(void Function(String data) callback);

sendToFlutter = allowInterop((String data) {
    print("Received data from JavaScript: $data");
});

JS

window.sendToFlutter = function(data) {
   console.log("Sending data to Flutter: " + data);
};

function sendDataToFlutter(data) {
    console.log("Sending data to Flutter from button click: " + data);
    if (typeof window.sendToFlutter === 'function') {
      window.sendToFlutter(data);
    } else {
      console.error("Flutter is not ready to receive data.");
    }
  }
2 Likes

Im not sure if this is the best way to do this, but a while back when i needed to get data from flutter side to js in a flutter web app, I did something like this on the dart side

window.sessionStorage['userName'] = "name"
final email = window.sessionStorage['email'];

and this on JS side

window.sessionStorage.getItem('userName');
window.sessionStorage.setItem('email', emailValue);

Where is the Flutter code you posted used?

Is it in a class, like in a widget or it’s at the top-level main function?

Providing the context will make it easier to help figure this out.

allowInterop will be deprecated since it is in dart:js which will be replaced by dart:js_interop.

I did something like this:

Dart

import 'dart:js_interop';

// Points to the same global object as window
@JS('globalThis')
external JSObject get globalThis;

// define the callback
typedef OnCallbackTFunction = void Function(String data);

// declare your callback
OnCallbackTFunction sendToFlutter = (String text) { print(text); }

// Somewhere in your code bind the JS function to the Dart function
globalThis.setProperty(
  'sendToFlutter'.toJS,
  sendToFlutter.toJS,
);

Now on JS side:

var functionName = "sendToFlutter";
if (typeof window[functionName] === "function") {
	window[functionName]("ciao"); // Call it
} else {
	console.log("JS 'sendToFlutter' not found.");
}

I don’t know much about JS or dart:js_interop, but this worked for me. Hope it helps.

4 Likes