如何在flutter web-view中导入tradingview库

问题描述 投票:0回答:1

我正在尝试将 tradeview 图表库导入到 iOS 上的 flutter webview 中。

我正在使用

webview_flutter: ^4.4.4
,下面是代码

<!DOCTYPE html>
<html lang="en">
<head>

    <title>TradingView Advanced Charts demo -- Mobile (black)</title>

    <!-- Fix for iOS Safari zooming bug -->
    <meta content="width=device-width,initial-scale=1.0,maximum-scale=1.0,minimum-scale=1.0" name="viewport">

    <script src="charting_library/charting_library.standalone.js"
            type="text/javascript">
    </script>
    <script src="datafeeds/udf/dist/bundle.js" type="text/javascript">
    </script>

    <script type="text/javascript">
        function initOnReady(to, from) {
            var datafeedUrl = "http://127.0.0.1:8000";
            // ConsoleLog.postMessage("check1234");
            var scripts = document.getElementsByTagName('script');
            Array.from(scripts).forEach(script => ConsoleLog.postMessage("script -> " + script.src));
            // var datafeedUrl = "https://demo-feed-data.tradingview.com";
            // var from = 1531009291;
            // var to = 1541009291;
            var widget = window.tvWidget = new TradingView.widget({
                symbol: 'AAPL',
                interval: '1D',
                container: "tv_chart_container",
                //  BEWARE: no trailing slash is expected in feed URL
                datafeed: new Datafeeds.UDFCompatibleDatafeed(datafeedUrl, undefined, {
                    maxResponseLength: 1000,
                    expectedOrder: 'latestFirst',
                }),
                library_path: "charting_library/",
                locale: "en",
                time_frames: [
                    {text: "1y", resolution: "1D", description: "1 Year"},
                    {text: "3m", resolution: "1D", description: "3 Months"},
                    {text: "1m", resolution: "1D", description: "1 Month"},
                    {text: "1w", resolution: "60", description: "1 Week"},
                    {text: "1d", resolution: "5", description: "1 Day"},
                    {text: "1000y", resolution: "1D", description: "All", title: "All"}
                ],
                timeframe: {"to": to, "from": from},

                disabled_features: [
                    'use_localstorage_for_settings',
                    'left_toolbar', 'header_widget', 'timeframes_toolbar', 'edit_buttons_in_legend', 'context_menus', 'control_bar', 'border_around_the_chart',
                ],
                overrides: {
                    "paneProperties.background": "#222222",
                    "paneProperties.vertGridProperties.color": "#454545",
                    "paneProperties.horzGridProperties.color": "#454545",
                    "scalesProperties.textColor": "#AAA"
                },
                debug: true,
                onReady: function (api) {
                    api.setVisibleRange({
                        from: from / 1000,
                        to: to / 1000
                    });
                }
            });
        }
    </script>

</head>

<body style="margin:0px;">
<div id="tv_chart_container"></div>
</body>

</html>
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:webview_flutter/webview_flutter.dart';

class TradingViewWidgetChart extends StatelessWidget {
  const TradingViewWidgetChart({
    required this.height,
    required this.width,
    required this.assetName,
    required this.toTime,
    super.key,
  });

  final double height;
  final double width;
  final String assetName;
  final int toTime;

  @override
  Widget build(BuildContext context) {
    return Container(
      height: height,
      width: width,
      color: Colors.greenAccent,
      child: Padding(
        padding: const EdgeInsets.all(8.0),
        child: TradingViewCompactChartWidgetHtml(
            assetName: assetName, toTime: toTime, fromTime: toTime - 1000000),
      ),
    );
  }
}

class TradingViewCompactChartWidgetHtml extends StatefulWidget {
  const TradingViewCompactChartWidgetHtml({
    required this.assetName,
    required this.toTime,
    required this.fromTime,
    super.key,
  });

  final String assetName;
  final int toTime;
  final int fromTime;

  @override
  State<TradingViewCompactChartWidgetHtml> createState() =>
      _TradingViewCompactChartWidgetHtmlState();
}

class _TradingViewCompactChartWidgetHtmlState
    extends State<TradingViewCompactChartWidgetHtml> {
  late final WebViewController controller; // Declare as nullable

  @override
  void initState() {
    super.initState();
    controller = WebViewController() // Initialize the controller here.
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..setBackgroundColor(Colors.white)
      ..addJavaScriptChannel(
        'ConsoleLog',
        onMessageReceived: (JavaScriptMessage message) {
          print("JS Console: ${message.message}");
        },
      )
      ..setNavigationDelegate(
        NavigationDelegate(
          onProgress: (int progress) {
            debugPrint('progress$progress');
          },
          onPageStarted: (String url) {
            debugPrint('started');
          },
          onPageFinished: (String url) {
            debugPrint('finished: $url');
            Future.delayed(Duration(milliseconds: 5000), () {
              debugPrint('hello world');
              controller.runJavaScript("""
        initOnReady(${widget.toTime}, ${widget.fromTime});
            """);
              debugPrint('hello world');
            });
          },
        ),
      )
      ..enableZoom(true)
      ..loadFlutterAsset('js_scripts/advanced.html');
  }

  @override
  Widget build(BuildContext context) {
    // return
    return WebViewWidget(controller: controller);
  }
}

我的期望:

Tradingview 图表库(独立)和

datafeeds/udf/dist/bundle.js
在 loadFlutterAsset 处导入,当页面加载完成时,我传递 initOnReady 函数,即加载 Tradingview 图表所需的参数

发生了什么:

我收到以下错误

[VERBOSE-2:dart_vm_initializer.cc(41)] Unhandled Exception: PlatformException(FWFEvaluateJavaScriptError, Failed evaluating JavaScript., A JavaScript exception occurred (WKErrorDomain:4:{WKJavaScriptExceptionLineNumber: Unsupported Type: 25, WKJavaScriptExceptionMessage: ReferenceError: Can't find variable: TradingView, WKJavaScriptExceptionSourceURL: Unsupported Type: file:///Users/username/Library/Developer/CoreSimulator/Devices/12E3ECA1-FD47-4B49-9F22-7B5B0147E8F4/data/Containers/Bundle/Application/8692A5E5-A6C1-4799-A20C-22CCC4C8F012/Runner.app/Frameworks/App.framework/flutter_assets/js_scripts/advanced.html, NSLocalizedDescription: A JavaScript exception occurred, WKJavaScriptExceptionColumnNumber: Unsupported Type: 59}), null)
#0      WKWebViewHostApiImpl.evaluateJavaScriptForInstances (package:webview_flutter_wkwebview/src/web_kit/web_kit_api_impls.dart:1082:7)
<asynchronous suspension>
#1      WebKitWebViewController.runJavaScript (package:webview_flutter_wkwebview/src/webkit_webview_contro<…>

我检查了什么?

使用

var scripts = document.getElementsByTagName('script');
            Array.from(scripts).forEach(script => ConsoleLog.postMessage("script -> " + script.src));

我可以看到该库正在导入

flutter: JS Console: script -> file:///Users/username/Library/Developer/CoreSimulator/Devices/12E3ECA1-FD47-4B49-9F22-7B5B0147E8F4/data/Containers/Bundle/Application/8692A5E5-A6C1-4799-A20C-22CCC4C8F012/Runner.app/Frameworks/App.framework/flutter_assets/js_scripts/charting_library/charting_library.standalone.js
flutter: JS Console: script -> file:///Users/username/Library/Developer/CoreSimulator/Devices/12E3ECA1-FD47-4B49-9F22-7B5B0147E8F4/data/Containers/Bundle/Application/8692A5E5-A6C1-4799-A20C-22CCC4C8F012/Runner.app/Frameworks/App.framework/flutter_assets/js_scripts/datafeeds/udf/dist/bundle.js

但是应用程序仍然会抛出错误,提示

Can't find variable: TradingView
存在于独立库中。

此外,当我在浏览器中的 httpserver 中正常运行此 html 时,它工作正常

我将不胜感激任何帮助。我尝试过添加日志和其他内容,但无法找到解决方案。谢谢你

javascript html flutter webview tradingview-api
1个回答
0
投票

您找到解决这个问题的方法了吗?

© www.soinside.com 2019 - 2024. All rights reserved.