flutterflutter-inappwebview

Flutter InAppWebview pass custom event data to the handler function


I want to pass the arguments which are coming in a custom event to the flutter handler function.

I tried this in onPageLoaded

Future<void> onPageLoaded(InAppWebViewController controller, Uri? url) async {
await controller.evaluateJavascript(source: """
            window.addEventListener('myCustomEvent', (event) => { 
              window.flutter_inappwebview.callHandler('myHandlerName');
            }, false);
          """);
    controller.addJavaScriptHandler(
      handlerName: 'myHandlerName',
      callback: (args) {
        //I want to get the args here but it is always an empty list
      },
}

dispatching a custom event from web like below:

const event = new CustomEvent("myCustomEvent", {
    detail: {foo: 1, bar: false}
});
window.dispatchEvent(event);

I want to get the args that are passing from the custom event in my handler function but it is always an empty list.


Solution

  • I found the way how to pass the data:

    I must pass the event.detail to my handler function in order to get the args in my handler's callback.

    window.flutter_inappwebview.callHandler('myHandlerName', event.detail);
                }, false);
    

    Now I can see the args which I am passing:

    controller.addJavaScriptHandler( handlerName: 'myHandlerName', callback: (args) { // List which contains the custom event data now }, );