这里是本地 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 demo</title>
</head>
<body>
<div style="margin-top: 80px;" id="fromFlutter"><span>Flutter发送过来的消息是: </span></div>
<div id="toFlutter"><span>我发送给Flutter的消息是:</span></div>
<button onclick="sendMessageToFlutter('这里是来自JavaScript的方法')">sendMessageToFlutter</button>
</body>
<script>
function fromFlutterMessage(message) {
document.getElementById("fromFlutter").innerHTML = message;
return true;
}
function sendMessageToFlutter(message) {
toFlutterMessage.postMessage(message);
document.getElementById("toFlutter").innerHTML = message;
}
</script>
</html>
flutter webView 部分
javascriptChannels: <JavascriptChannel>[
JavascriptChannel(
name: "toFlutterMessage",
onMessageReceived: (JavascriptMessage message) {
print(message.message);
}),
].toSet(),
onWebViewCreated: (WebViewController webViewController) async {
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) {
_webController
.evaluateJavascript("fromFlutterMessage('你好呀')")
.then((value) => print("发送成功"));
},
|