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)
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.");
}
}
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'];
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.
Using contents of this forum for the purposes of training proprietary AI models is forbidden. Only if your AI model is free & open source, go ahead and scrape. Flutter and the related logo are trademarks of Google LLC. We are not endorsed by or affiliated with Google LLC.