Flutter金融图表插件candlesticks_plus的使用

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

Flutter金融图表插件candlesticks_plus的使用

candlesticks

pub package

一个适用于所有平台的高性能全功能K线图!

网页演示:

  • Binance K线图
  • Binance K线图 GitHub仓库

预览

iOS macOS

安装

  1. 将以下内容添加到你的pubspec.yaml文件中:
dependencies:
  candlesticks: ^2.1.0
  1. 使用IDE的图形界面或通过命令行获取包:
$ flutter pub get

使用

首先导入candlesticks_plus库:

import 'package:candlesticks_plus/candlesticks_plus.dart';

Candle

Candle类包含六个必需变量,用于存储单个蜡烛的数据:日期、最高价、最低价、开盘价、收盘价和成交量。

final candle =  Candle(date: DateTime.now(), open: 1780.36, high: 1873.93, low: 1755.34, close: 1848.56, volume: 0);

Candlesticks

Candlesticks小部件需要一个蜡烛列表。candles数组的排列方式应使最新的项目位于位置0。onLoadMoreCandles是一个可选回调,当最后一个蜡烛变得可见时会调用它。如果你想在顶部工具栏中添加更多操作,比如在Binance K线图中那样,你可以创建自定义的ToolBarAction并将其添加到actions参数中。

class MyApp extends StatefulWidget {
  [@override](/user/override)
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  List<Candle> candles = [];
  bool themeIsDark = false;

  [@override](/user/override)
  void initState() {
    fetchCandles().then((value) {
      setState(() {
        candles = value;
      });
    });
    super.initState();
  }

  Future<List<Candle>> fetchCandles() async {
    final uri = Uri.parse(
        "https://api.binance.com/api/v3/klines?symbol=BTCUSDT&interval=1h");
    final res = await http.get(uri);
    return (jsonDecode(res.body) as List<dynamic>)
        .map((e) => Candle.fromJson(e))
        .toList()
        .reversed
        .toList();
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: themeIsDark ? ThemeData.dark() : ThemeData.light(),
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        appBar: AppBar(
          title: Text("BTCUSDT 1H Chart"),
          actions: [
            IconButton(
              onPressed: () {
                setState(() {
                  themeIsDark = !themeIsDark;
                });
              },
              icon: Icon(
                themeIsDark
                    ? Icons.wb_sunny_sharp
                    : Icons.nightlight_round_outlined,
              ),
            )
          ],
        ),
        body: Center(
          child: Candlesticks(
            candles: candles,
            watermark: 'Matinex',
            onLoadMoreCandles: () async {
              candles.addAll(candles.sublist(0, 100));
            },
          ),
        ),
      ),
    );
  }
}

更多关于Flutter金融图表插件candlesticks_plus的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter金融图表插件candlesticks_plus的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,下面是一个关于如何在Flutter项目中使用candlesticks_plus插件来绘制金融图表的代码示例。这个插件主要用于显示K线图(蜡烛图),是金融数据分析中常见的一种图表类型。

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

dependencies:
  flutter:
    sdk: flutter
  candlesticks_plus: ^最新版本号  # 请替换为当前最新版本号

然后运行flutter pub get来安装依赖。

接下来是一个完整的Flutter应用示例,展示如何使用candlesticks_plus插件:

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Candlestick Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: CandlestickDemoPage(),
    );
  }
}

class CandlestickDemoPage extends StatefulWidget {
  @override
  _CandlestickDemoPageState createState() => _CandlestickDemoPageState();
}

class _CandlestickDemoPageState extends State<CandlestickDemoPage> {
  final List<OhlcData> data = [
    OhlcData(
      dateTime: DateTime(2023, 10, 1),
      open: 150.0,
      high: 155.0,
      low: 145.0,
      close: 152.0,
      volume: 1000,
    ),
    OhlcData(
      dateTime: DateTime(2023, 10, 2),
      open: 152.0,
      high: 160.0,
      low: 150.0,
      close: 158.0,
      volume: 1200,
    ),
    // 添加更多数据点...
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Candlestick Chart Demo'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: CustomPaint(
          size: Size(double.infinity, 400),
          painter: CandlestickPainter(
            data: data,
            padding: EdgeInsets.symmetric(horizontal: 20.0),
            style: CandlestickStyle(
              increasingColor: Colors.green,
              decreasingColor: Colors.red,
              borderColor: Colors.black,
              borderWidth: 1.0,
              candleWidthRatio: 0.6,
            ),
          ),
        ),
      ),
    );
  }
}

class OhlcData {
  final DateTime dateTime;
  final double open;
  final double high;
  final double low;
  final double close;
  final int volume; // 可选,用于显示成交量等信息,本例中未使用

  OhlcData({
    required this.dateTime,
    required this.open,
    required this.high,
    required this.low,
    required this.close,
    this.volume = 0,
  });
}

在这个示例中,我们创建了一个简单的Flutter应用,其中包含一个K线图。CandlestickPaintercandlesticks_plus插件提供的一个绘制K线图的画家(Painter),它接受一个OhlcData列表作为数据源,并绘制出相应的K线图。

注意:

  • OhlcData类用于存储每个K线数据点的信息,包括日期时间、开盘价、最高价、最低价、收盘价和成交量(本例中未使用)。
  • CandlestickPainter接受一个style参数,用于自定义K线图的样式,比如颜色、边框宽度等。
  • CustomPaint用于在Flutter中绘制自定义图形,这里用它来包裹CandlestickPainter

这个示例展示了如何使用candlesticks_plus插件在Flutter应用中绘制基本的K线图。你可以根据需要进一步自定义和扩展这个示例。

回到顶部