Flutter_Flutter与JS相互调用

Flutter与JS相互调用

  • WebView插件的使用
    • 导入插件
    • 插件调用
    • WebView配置
  • JS调用Flutter方法
  • Flutter调用JS方法
  • JS代码示例


WebView插件的使用

导入插件

webview_flutter: ^4.2.2

插件调用

import 'package:webview_flutter/webview_flutter.dart';

WebView配置

  WebViewController _controller;
WebView(
   initialUrl: "https://xxxxx",
   onWebViewCreated: (controller) {
     _controller = controller;
   },
   javascriptMode: JavascriptMode.unrestricted,
   javascriptChannels: jsCallNativeChannel(),
   gestureNavigationEnabled: true,
)

JS调用Flutter方法

Set<JavascriptChannel> jsCallNativeChannel() {
    return <JavascriptChannel>{
      JavascriptChannel(name: "funcName1", onMessageReceived: funcNameImplement1),
      JavascriptChannel(name: "funcName2", onMessageReceived: funcNameImplement2),
    };
 }

void funcNameImplement1(JavascriptMessage message) {
   debugPrint("接收到的数据${message.message}");
}
void funcNameImplement2(JavascriptMessage message) {
   debugPrint("接收到的数据${message.message}");
}

Flutter调用JS方法

// json数据格式化
import 'dart:convert';
String funcName = "JSFunctionName";
String dataJson = json.encode({"code": 200, "data": "sendToJsData"});
String javaScript = "$funcName('$dataJson')";
// 无返回值调用
_controller.runJavaScript(javaScript);
// 有返回值的调用
_controller.runJavaScriptReturningResult(javaScript).then((value) {});

JS代码示例

DOCTYPE html>
<html>
<title>交互title>
<head>
    <meta charset="UTF-8">
head>

<body>
<div style="margin-top: 20px">
    <h2 id="aaaa">JS与Flutter交互h2>
    <input type="button" value="唤起本地方法" id="dsadadd" onclick="toFlutter('toFlutterData')" >
div>
<script>
        function toFlutter(data){
            window.webkit.messageHandlers.funcName1.postMessage(JSON.stringify({ operation: data }))
        }
        window['JSFunctionName'] = (data) => {
        	document.getElementById('aaaa').innerHTML=data
        }
    script>
body>

html>

你可能感兴趣的:(Flutter,flutter,javascript)