Listening to JS CustomEvent in Dart

Issue

I know that my question is not new, but all solutions I’ve found here and in the Internet are not working 🙁 Or, I’m doing something completely wrong.

I need to create a communication between Dart and JS, and I would love to use events, as the idea seems to be neat and simple.

So, I tried this tutorial: https://dart.academy/easy-dart-js-interopt/

My JS code:

var customEvent = new CustomEvent("fromJavascriptToDart");
window.onload = document.dispatchEvent(customEvent);
document.addEventListener("fromJavascriptToDart", test, false);
function test() {
    console.log("Listening");
}

The event is dispatched, as I see Listening in console log.

But when it comes to dart, nothing is working.

I’ve tried the following methods and everything failed:

document.on['fromJavascriptToDart'].listen((CustomEvent event) {
                    print("HEY! I'M LISTENING!");
                });
window.on["fromJavascriptToDart"].listen((e) => print( "HEY! I'M LISTENING!"));
window.on['foo'].add((e) => print(e.detail)); //This is not working, as there is no add method in Stream Event anymore
@Listen('fromJavascriptToDart')
    void eventTest(){
        print("HEY! I'M LISTENING!");
    }

Any help is mostly appreciated.

Solution

DartPad example

document.on['fromJavascriptToDart'].listen((CustomEvent event) {
  print("HEY! I'M LISTENING!");
});

Works fine.

  • @Listen() is Polymer specific
  • add doesn’t exist (listen as show above should be used)
  • the event doesn’t seem to reach window, but I’m sure this will behave the same in pure JS.

Answered By – Günter Zöchbauer

Answer Checked By – Robin (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *