我是flutter的新手。我使用webview_flutter开发了js到flutter dart通信,像这样:
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Plugin example'),
actions: <Widget>[
MenuList(_controller.future),
],
),
body: Builder(builder: (BuildContext context) {
return WebView(
initialUrl: localServerUrl,
javascriptMode: JavascriptMode.unrestricted,
onWebViewCreated: (WebViewController webViewController) {
_controller.complete(webViewController);
},
javascriptChannels: <JavascriptChannel>[
_scanBarcode(context),
].toSet(),
onPageFinished: (String url) {
//TODO : events after page loading finished
},
);
}),
),
);
}
JavascriptChannel _scanBarcode(BuildContext context) {
return JavascriptChannel(
name: 'Barcode',
onMessageReceived: (JavascriptMessage message) {
String result = scanBarcode(context);
******I got result of scanned barcode in result variable******
});
}
服务器 HTML 文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="script.js"></script>
</head>
<body>
<button id="btnBarcode" style="margin-top:20px; height:30px;">Scan Barcode</button>
</body>
</html>
这是JS文件
function scanBarcode(message) {
if (window.Barcode && window.Barcode.postMessage) {
Barcode.postMessage(message);
}
}
window.onload = function () {
document.getElementById('btnBarcode').onclick = function () {
scanBarcode("Scan Barcode");
}
}
我已经成功地在Dart文件的javascript通道_scanBarcode中获取了扫描条形码的结果。
现在我想要将这个条形码的结果回调到JS文件中的scanBarcode函数中。
我已经研究了很长时间,但是什么都没有得到。
我现在卡住了。 有人可以帮帮我吗?非常感谢您的帮助。
return result
,然后我们可以使用Promise的then()方法在JavaScript函数中获取结果吗?就像这样:scanBarcode(..).then(function (barcodeResult) {// result from Dart})
- Ankit SathvaraBarcode
是什么意思?它是 js 文件的类名吗? 如果我在 JavaScript 函数中调用window.postMessage(result);
,我还能得到结果吗? - MNFS