Flutter_Flutter and JS call each other


Use of WebView plug-in

import plugin

webview_flutter: ^4.2.2

plugin call

import 'package:webview_flutter/webview_flutter.dart';

WebView configuration

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

JS calls the Flutter method

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 calls JS method

// 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 code example

<!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>

Guess you like

Origin blog.csdn.net/FlyingKuiKui/article/details/131450163