Wednesday 30 December 2020

Call Dart method from JS in Flutter Web

For a Webview relate feature I had used Method channels to open Webview through Native Android & iOS code and I am opening a website in it, I was getting callback from JS to native code in mobile platforms. For Android I was providing a class whose method is getting called from JS, It looks something like this:

webView.settings.javaScriptEnabled = true
webView.addJavascriptInterface(WebAppInterface(this), "nativeCommunicator")

webView.loadUrl("SOME_URL")

…

class WebAppInterface(private val mContext: Activity) {
  @JavascriptInterface
  fun postMessage(text: String) {
    println("WebAppInterface.message($text)")
    //send back to flutter
  }
}

Which seems quite straightforward way to get callback from js to my code.

Now I am trying to do this in Flutter Web I opened the website by calling

import 'package:js/js.dart';
...
js.context.callMethod('open', 'SOME_URL', '_self');

Which works fine, Now I am trying to get callback by creating this class

@JS()
library native_communicator;

import 'package:js/js.dart';
@JS('nativeCommunicator')
class NativeCommunicator{

 @JS('postMessage')
 external static set _postMessage(void Function(String text) f);


 @JS()
 external static void postMessage();

}

void setJSCallbackFunction(void Function(String text) postMessageFunction) {
 NativeCommunicator._postMessage = allowInterop(postMessageFunction);
}

I am calling setJSCallbackFunction and passing my function as param, but it keeps giving me runtime error that It can not find ‘postMessage’, I tried some other way which leads to can not find ‘nativeCommunicator’ error, Can anyone point out how to do this right? I need to call a dart method from js.



from Call Dart method from JS in Flutter Web

No comments:

Post a Comment