【问题标题】:Flutter two way communication js to dart and callback result from dart to jsFlutter 两种方式通信 js 到 dart 以及从 dart 到 js 的回调结果
【发布时间】:2020-04-03 07:20:15
【问题描述】:

我是新来的颤振。我已经开发了 js 来使用 webview_flutter 进行飞镖通信。像这样:

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 中的条码扫描结果。

现在我想在 scanBarcode 函数中将此条码结果回调回 JS 文件。

我研究了这么多时间,却一无所获。

我被困在这里。谁能帮我??非常感谢您。

【问题讨论】:

    标签: javascript flutter dart callback flutter-web


    【解决方案1】:

    您可以使用webViewctrl.evaluateJavascript
    可以参考https://www.elasticfeed.com/7ee71117c626c2021eb919c182ec483a/
    代码 sn -p

    onPressed: () {
              webViewctrl.evaluateJavascript(
                  "scanBarcode('123')");
            }
    

    我将 console.log(message); 添加到 javascript 函数 scanBarcode 以证明它有效

    function scanBarcode(message) {
       console.log(message);
       if (window.Barcode && window.Barcode.postMessage) {
          console.log(document.documentElement.innerHTML);
          Barcode.postMessage(message);
       }
    }
    

    输出

    I/chromium( 5209): [INFO:CONSOLE(2)] "123", source: http://yoursite/jschannel/script.js (2)
    

    完整的测试代码

    import 'package:flutter/material.dart';
    import 'package:webview_flutter/webview_flutter.dart';
    import 'dart:async';
    
    void main() => runApp(MyApp());
    
    class MyApp extends StatelessWidget {
      // This widget is the root of your application.
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'Flutter Demo',
          theme: ThemeData(
            primarySwatch: Colors.blue,
          ),
          home: MyHomePage(title: 'Flutter Demo Home Page'),
        );
      }
    }
    
    class MyHomePage extends StatefulWidget {
      MyHomePage({Key key, this.title}) : super(key: key);
    
      final String title;
    
      @override
      _MyHomePageState createState() => _MyHomePageState();
    }
    
    WebViewController webViewctrl;
    
    class _MyHomePageState extends State<MyHomePage> {
      final Completer<WebViewController> _controller =
          Completer<WebViewController>();
    
      int _counter = 0;
    
      void _incrementCounter() {
        setState(() {
          _counter++;
        });
      }
    
      @override
      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: 'http://yoursite/jschannel/index.html',
                  javascriptMode: JavascriptMode.unrestricted,
                  onWebViewCreated: (WebViewController webViewController) {
                    _controller.complete(webViewController);
                    webViewctrl = webViewController;
                  },
                  javascriptChannels: <JavascriptChannel>[
                    _scanBarcode(context),
                  ].toSet(),
                  onPageFinished: (String url) {
                    //TODO : events after page loading finished
                  },
                );
              }),
              floatingActionButton: FloatingActionButton(
                onPressed: () {
                  webViewctrl.evaluateJavascript(
                      "scanBarcode('123')");
                },
                child: Icon(Icons.navigation),
                backgroundColor: Colors.green,
              )),
        );
      }
    }
    
    JavascriptChannel _scanBarcode(BuildContext context) {
      return JavascriptChannel(
          name: 'Barcode',
          onMessageReceived: (JavascriptMessage message) {
            /*String result = scanBarcode(context);
            ******I got result of scanned barcode in result variable*******/
          });
    }
    

    【讨论】:

    • 感谢您的回答.. 它的工作。我们不能在 dart 文件中直接返回像 return result 这样的结果吗,并且我们将使用前提 then() 在 JavaScript 函数中得到这样的东西.. scanBarcode(..).then(function (barcodeResult) {// result from Dart})
    • 很高兴为您提供帮助。如果有帮助,请将此标记为答案,谢谢。
    • 您可以进行字符串连接以让 javascript 执行/评估该字符串。在此之前,您必须确保这个长字符串有效。
    • @chunhunghan 嗨谢谢你的回答,我想问一下 JavascriptChannel 参数名称上的Barcode 是什么意思?它是js文件的类名吗?如果我在 javascript func 上调用 window.postMessage(result);,我还能得到结果吗?
    猜你喜欢
    • 2021-04-02
    • 1970-01-01
    • 1970-01-01
    • 2023-01-20
    • 2019-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-25
    相关资源
    最近更新 更多