flutter 用 webview_flutter 与 h5 交互

这里是本地 h5 页面,需要在 pubspec.yaml 里添加资源

DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>html demotitle>
head>

<body>
  <div style="margin-top: 80px;" id="fromFlutter"><span>Flutter发送过来的消息是: span>div>
  <div id="toFlutter"><span>我发送给Flutter的消息是:span>div>
  <button onclick="sendMessageToFlutter('这里是来自JavaScript的方法')">sendMessageToFlutterbutton>
body>
<script>
  // 这个方法是用来给Flutter调用的(即:Flutter调用js方法)
  function fromFlutterMessage(message) {
    document.getElementById("fromFlutter").innerHTML = message;
    return true;
  }

  // 这个方法是用来发送一个消息给Flutter的(即:js调用Flutter方法)
  function sendMessageToFlutter(message) {
    toFlutterMessage.postMessage(message);
    document.getElementById("toFlutter").innerHTML = message;
  }
script>

html>

flutter webView 部分

              javascriptChannels: <JavascriptChannel>[
                JavascriptChannel(
                    ///方法名要与h5页面方法一致
                    name: "toFlutterMessage",  
                    onMessageReceived: (JavascriptMessage message) {
                      print(message.message);
                    }),
              ].toSet(),
              onWebViewCreated: (WebViewController webViewController) async {
                ///h5页面资源位置
                String filePath = 'assets/h5.html';  
                String fileText = await rootBundle.loadString(filePath);
                _webController.loadUrl(Uri.dataFromString(fileText,
                        mimeType: 'text/html',
                        encoding: Encoding.getByName('utf-8'))
                    .toString());
              },
              onPageFinished: (String url) {
                  ///Flutter调用js方法
                  _webController
                      .evaluateJavascript("fromFlutterMessage('你好呀')")
                      .then((value) => print("发送成功"));
              },

你可能感兴趣的:(flutter,flutter,交互,android)