I have a method in Flutter that receives a closure. I want to pass that closure to JS and call it back anytime, from somewhere in JS. I’d also like to use dart:js_interop
to be WASM compatible (I have seen an example using setProperty
and allowInterop
but they come from dart:js
which is deprecated).
typedef OnCallbackTFunction = void Function(bool something);
class MyClass {
[...]
// This method could be called more than once with different closures
void doSomething({OnCallbackTFunctio? onSomething})
{
// On JS side I should store the [onSomething] closure to be called back.
// Something like this(?):
wasmSetCallback(onSomething);
}
}
On JS I need something to store the callback. Well, this is a C++ class which uses EM_ASM
to inline some JS code:
typedef void (*dartCallback_t)(bool something);
// Each call to the Dart `doSomething()` will create only one instance of this class.
class MyCallbackClass {
public:
void setCallback(dartCallback_t *callback)
{
EM_ASM({
// What to put here?
});
}
void callDartMethod()
{
EM_ASM({
// What to put here?
});
}
}
This C++ code will be compiled with emscripten to produce also the .js.
All this to achieve something like:
final n = MyClass.instance.doSomething(onSomething: () {print('callback N from JS!');});
final m = MyClass.instance.doSomething(onSomething: () {print('callback M from JS!');});
I read that JSObjectUnsafeUtilExtension could be used to set JS property, maybe a JS function to use for the callback, but I’ve not found docs explaining how to use it.
Any help is greatly appreciated.