web_flutter_connect
TypeScript icon, indicating that this package has built-in type declarations

1.0.6 • Public • Published

Web-Flutter connect package

Flutter

  1. In Client side
///Javascript
const {connectFlutter} = require("web_flutter_connect")
const {WebView, Flutter} = connectFlutter(window)
  1. Call Flutter
///Javascript
await Flutter.call(hanlderName: string, ...params: any[])
  1. Send message to Flutter
///Javascript
await Flutter.send(data: any)
--> await Flutter.call("onMessage", data)

In Flutter: Needs execute Listen event "onMessage" from WebView

///Dart
///Listen message from web
this.controller?.addJavaScriptHandler(
    handlerName: WebviewModuleKeys.onMessage,
    callback: (List<dynamic> params) async {
      if (widget.onMessage != null) {
        widget.onMessage!(params[0]);
      }
    });
  1. Close webview
///Javascript
 await Flutter.close()
--> await Flutter.call("closeWebview", data)
  1. Notify Web content did load
///Javascript
 await Flutter.setDidLoad()
--> await Flutter.call("onContentDidLoad", data)
  1. Print to Flutter console
///Javascript
 await Flutter.print(data)
--> await Flutter.call("onWebViewPrint", data)

In Flutter:

///Dart
        ///Listen print from web
        this.controller?.addJavaScriptHandler(
            handlerName: WebviewModuleKeys.onPrint,
            callback: (List<dynamic> params) async {
              print("*** PRINT FROM WEBVIEW: ***");
              if (params.isNotEmpty) {
                print("${params.first}");
              }
              print("*** END PRINT FROM WEBVIEW ***");
            });

WebView

  1. WebView.listenFromFlutter: Listen message from Flutter
///Javascript
const subscription = WebView.listenFromFlutter((message: any) => {
    Flutter.print({
        "title": "Receive message from Flutter",
        "data": message,
    });
})
....
//Unsubscribe
subscription.unsubscribe();
  1. WebView.send(message: any)
  • Call in Flutter to send a message to WEB
///Dart
try {
  final strMessage = jsonEncode(message);
  this.controller?.evaluateJavascript(source: """
    window.WebView.send('$strMessage');
  """);
} catch (e) {
  throw {
    "error": "Cannot send unencodable message to WebView",
    "message": message,
  };
}

Package Sidebar

Install

npm i web_flutter_connect

Weekly Downloads

48

Version

1.0.6

License

ISC

Unpacked Size

32.2 kB

Total Files

38

Last publish

Collaborators

  • mrbaobao