Flutter蜡烛图绘制插件candlestick_chart的使用

发布于 1周前 作者 zlyuanteng 来自 Flutter

Flutter蜡烛图绘制插件candlestick_chart的使用

插件介绍

candlestick_chart 是一个支持缩放和拖动功能的蜡烛图插件,它可以从 flutter-interactive-chart 源代码中 fork 出来。该插件允许用户在图表上进行交互操作,如放大、缩小和拖动查看数据。

示例代码

下面是一个完整的示例代码,展示了如何使用 candlestick_chart 插件来绘制蜡烛图,并添加一些自定义样式和交互功能。

import 'package:candlestick_chart/candlestick_chart.dart';
import 'package:flutter/material.dart';

import 'mock_data.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  [@override](/user/override)
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  final List<CandleData> _data = MockDataTesla.candles;
  bool _darkMode = true;
  bool _showAverage = false;

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        brightness: _darkMode ? Brightness.dark : Brightness.light,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: const Text("Interactive Chart Demo"),
          actions: [
            IconButton(
              icon: Icon(_darkMode ? Icons.dark_mode : Icons.light_mode),
              onPressed: () =&gt; setState(() =&gt; _darkMode = !_darkMode),
            ),
            IconButton(
              icon: Icon(
                _showAverage ? Icons.show_chart : Icons.bar_chart_outlined,
              ),
              onPressed: () {
                setState(() =&gt; _showAverage = !_showAverage);
                if (_showAverage) {
                  _computeTrendLines();
                } else {
                  _removeTrendLines();
                }
              },
            ),
          ],
        ),
        body: SafeArea(
          minimum: const EdgeInsets.all(24.0),
          child: CandlestickChart(
            /** Only [candles] is required */
            candles: _data,
            /** Uncomment the following for examples on optional parameters */

            /** Example styling */
            // style: ChartStyle(
            //   priceGainColor: Colors.teal[200]!,
            //   priceLossColor: Colors.blueGrey,
            //   volumeColor: Colors.teal.withOpacity(0.8),
            //   trendLineStyles: [
            //     Paint()
            //       ..strokeWidth = 2.0
            //       ..strokeCap = StrokeCap.round
            //       ..color = Colors.deepOrange,
            //     Paint()
            //       ..strokeWidth = 4.0
            //       ..strokeCap = StrokeCap.round
            //       ..color = Colors.orange,
            //   ],
            //   priceGridLineColor: Colors.blue[200]!,
            //   priceLabelStyle: TextStyle(color: Colors.blue[200]),
            //   timeLabelStyle: TextStyle(color: Colors.blue[200]),
            //   selectionHighlightColor: Colors.red.withOpacity(0.2),
            //   overlayBackgroundColor: Colors.red[900]!.withOpacity(0.6),
            //   overlayTextStyle: TextStyle(color: Colors.red[100]),
            //   timeLabelHeight: 32,
            //   volumeHeightFactor: 0.2, // volume area is 20% of total height
            // ),
            /** Customize axis labels */
            // timeLabel: (timestamp, visibleDataCount) =&gt; "📅",
            // priceLabel: (price) =&gt; "${price.round()} 💎",
            /** Customize overlay (tap and hold to see it)
             ** Or return an empty object to disable overlay info. */
            // overlayInfo: (candle) =&gt; {
            //   "💎": "🤚    ",
            //   "Hi": "${candle.high?.toStringAsFixed(2)}",
            //   "Lo": "${candle.low?.toStringAsFixed(2)}",
            // },
            /** Callbacks */
            // onTap: (candle) =&gt; print("user tapped on $candle"),
            // onCandleResize: (width) =&gt; print("each candle is $width wide"),
          ),
        ),
      ),
    );
  }

  _computeTrendLines() {
    final ma7 = CandleData.computeMA(_data, 7);
    final ma30 = CandleData.computeMA(_data, 30);
    final ma90 = CandleData.computeMA(_data, 90);

    for (int i = 0; i &lt; _data.length; i++) {
      _data[i].trends = [ma7[i], ma30[i], ma90[i]];
    }
  }

  _removeTrendLines() {
    for (final data in _data) {
      data.trends = [];
    }
  }
}

更多关于Flutter蜡烛图绘制插件candlestick_chart的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter蜡烛图绘制插件candlestick_chart的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,下面是一个关于如何在Flutter中使用candlestick_chart插件来绘制蜡烛图的示例代码。这个插件主要用于金融数据可视化,特别是股票和加密货币的价格图表。

首先,确保你已经在pubspec.yaml文件中添加了candlestick_chart依赖:

dependencies:
  flutter:
    sdk: flutter
  candlestick_chart: ^x.y.z  # 请替换为最新版本号

然后运行flutter pub get来获取依赖。

接下来,是一个简单的Flutter应用示例,展示如何使用candlestick_chart来绘制蜡烛图:

import 'package:flutter/material.dart';
import 'package:candlestick_chart/candlestick_chart.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Candlestick Chart Example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: Text('Candlestick Chart Example'),
        ),
        body: Center(
          child: CandlestickChartExample(),
        ),
      ),
    );
  }
}

class CandlestickChartExample extends StatelessWidget {
  // 示例数据:蜡烛图数据通常由开盘价、最高价、最低价和收盘价组成
  final List<CandlestickData> data = [
    CandlestickData(
      DateTime.utc(2023, 10, 1, 10, 0),
      100.0, 110.0, 95.0, 105.0,
    ),
    CandlestickData(
      DateTime.utc(2023, 10, 1, 11, 0),
      105.0, 115.0, 100.0, 110.0,
    ),
    CandlestickData(
      DateTime.utc(2023, 10, 1, 12, 0),
      110.0, 120.0, 105.0, 115.0,
    ),
    // 添加更多数据点...
  ];

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 400,
      child: CandlestickChart(
        data: data,
        padding: EdgeInsets.all(16.0),
        domainAxisFormatter: (DateTime date, _) => DateFormat('HH:mm').format(date),
        tooltipBuilder: (context, index, data) {
          final candlestick = data[index];
          return Tooltip(
            message: 'Open: ${candlestick.open.toStringAsFixed(2)}\n'
                'High: ${candlestick.high.toStringAsFixed(2)}\n'
                'Low: ${candlestick.low.toStringAsFixed(2)}\n'
                'Close: ${candlestick.close.toStringAsFixed(2)}',
            child: Container(),
          );
        },
      ),
    );
  }
}

// CandlestickData 类,用于存储蜡烛图的数据点
class CandlestickData {
  final DateTime dateTime;
  final double open;
  final double high;
  final double low;
  final double close;

  CandlestickData(this.dateTime, this.open, this.high, this.low, this.close);
}

在这个示例中,我们创建了一个简单的Flutter应用,其中包含一个CandlestickChartCandlestickData类用于存储每个蜡烛图数据点的信息,包括日期时间、开盘价、最高价、最低价和收盘价。

CandlestickChart组件接受一个数据列表,并使用这些数据绘制蜡烛图。我们还自定义了tooltipBuilder来显示每个蜡烛图数据点的详细信息。

请注意,实际使用中你可能需要从API或其他数据源获取蜡烛图数据,并将其转换为CandlestickData对象列表。此外,根据需求,你可能还需要调整图表的样式和配置。

回到顶部