Flutter与JS相互调用

1.依赖webview

  webview_flutter: ^3.0.1

2.导入头文件

import 'package:webview_flutter/webview_flutter.dart';

3.创建webview

WebView(
        initialUrl: "",
        //widget.url ??  "https://www.baidu.com",
        //JS执行模式 是否允许JS执行
        javascriptMode: JavascriptMode.unrestricted,
        //webview创建好
        onWebViewCreated: (controller) {
          _controller = controller;
          _loadHtmlStr();
        },
        onPageFinished: (String url) {
          //加载完成 移除导航栏
          _controller?.runJavascript("getAddressBook('你们好')");

          setState(() {
            if (widget.url == null) {
              // this.showAppBar = false;
            }
          });
        },
        javascriptChannels: [
          JavascriptChannel(
              name: "integral",
              onMessageReceived: (JavascriptMessage message) {
                print("交互");
                print("参数: ${message.message}");
                Map res = changeStringToJsonMap(message.message);
                print(res["operation"]);


                // _controller?.evaluateJavascript("getAddressBook('sdad')");

              }
          ),
          JavascriptChannel(
              name: "MessageDeal",
              onMessageReceived: (JavascriptMessage message) {
                print("交互");
                print("参数: ${message.message}");
                print(_controller);
                _controller?.evaluateJavascript(
                    "showMessage('我(Flutter)收到了你的消息)");
                // _controller?.evaluateJavascript("document.title");


              }
          ),
          JavascriptChannel(
              name: "callWithDict",
              onMessageReceived: (JavascriptMessage message) {
                print("交互");
                print("参数: ${message.message}");
              }
          ),
        ].toSet(),
      ),
  changeStringToJsonMap(String jsonStr) {
    Map result = convert.jsonDecode(jsonStr);
    return result;
  }

3.1 flutte 调用 js 关键代码

onPageFinished: (String url) {
          //加载完成 移除导航栏
          _controller?.runJavascript("getAddressBook('你们好')");
 },

老的evaluateJavascript已经废弃, 请使用 runJavascript 或者 runJavascriptReturningResult
其中getAddressBook是js里的方法

3.2 js 调用flutter

JavascriptChannel(
              name: "MessageDeal",
              onMessageReceived: (JavascriptMessage message) {
                print("交互");
                print("参数: ${message.message}");
                print(_controller);
              }
      ),

附一个 html 练习



23

    



JS与OC交互

你可能感兴趣的:(Flutter与JS相互调用)