Flutter图表绘制插件k_chart的使用

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

Flutter图表绘制插件k_chart的使用

k_chart

这可能是Flutter中最优秀的K线图插件。支持拖动、缩放、长按和滑动操作,并且非常易于使用。

显示效果

图片

Screenshot Screenshot Screenshot

动图

demo demo

入门指南

安装

pubspec.yaml文件中添加依赖:

dependencies:
  k_chart: ^0.7.1

或者使用最新的版本:

k_chart:
    git:
      url: https://github.com/mafanwei/k_chart

使用

数据处理

当你更改数据时,必须调用以下函数:

DataUtil.calculate(datas); // 这个函数有一些可选参数:n 是 BOLL N天收盘价,k 是 BOLL 参数。

使用K线图

Container(
  height: 450,
  width: double.infinity,
  child: KChartWidget(
    chartStyle, // 必填,用于样式设置
    chartColors, // 必填,用于样式设置
    datas, // 必填,数据必须是有序列表(历史->现在)
    isLine: isLine, // 决定是否显示K线或分时图
    mainState: _mainState, // 决定主视图显示的内容
    secondaryState: _secondaryState, // 决定副视图显示的内容
    fixedLength: 2, // 显示的小数精度
    timeFormat: TimeFormat.YEAR_MONTH_DAY, // 时间格式
    onLoadMore: (bool a) {}, // 当数据滚动到末尾时调用。a 为 true 表示用户拉到了数据右侧的末尾,a 为 false 表示用户拉到了数据左侧的末尾
    maDayList: [5, 10, 20], // MA 显示,此参数必须等于 DataUtil.calculate 的 maDayList
    translations: kChartTranslations, // 图表语言
    volHidden: false, // 隐藏成交量
    showNowPrice: true, // 显示当前价格
    isOnDrag: (isDrag) {}, // true 表示正在拖动。拖动时不加载数据
    onSecondaryTap: () {}, // 副视图点击事件
    isTrendLine: false, // 设置为 true 后,可以通过长按并移动手指来使用趋势线
    xFrontPadding: 100, // 前部填充
  ),
),

使用深度图

DepthChart(_bids, _asks, chartColors) // 注意:数据必须是有序列表

捐赠

如果你觉得这个插件对你有帮助,可以给作者买杯咖啡。

alipay wechat

致谢

感谢 gwhcn/flutter_k_chart 的贡献。

其他

如果这个K线图插件存在一些bug,或者你希望添加新的指标,你可以创建一个pull request。我会很高兴接受它,并希望我们能一起让它变得更好。

示例代码

以下是一个完整的示例代码,展示了如何使用k_chart插件:

import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:http/http.dart' as http;
import 'package:k_chart/chart_translations.dart';
import 'package:k_chart/flutter_k_chart.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.green,
      ),
      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();
}

class _MyHomePageState extends State<MyHomePage> {
  List<KLineEntity>? datas;
  bool showLoading = true;
  MainState _mainState = MainState.MA;
  bool _volHidden = false;
  SecondaryState _secondaryState = SecondaryState.MACD;
  bool isLine = true;
  bool isChinese = true;
  bool _hideGrid = false;
  bool _showNowPrice = true;
  List<DepthEntity>? _bids, _asks;
  bool isChangeUI = false;
  bool _isTrendLine = false;
  bool _priceLeft = true;
  VerticalTextAlignment _verticalTextAlignment = VerticalTextAlignment.left;

  ChartStyle chartStyle = ChartStyle();
  ChartColors chartColors = ChartColors();

  @override
  void initState() {
    super.initState();
    getData('1day');
    rootBundle.loadString('assets/depth.json').then((result) {
      final parseJson = json.decode(result);
      final tick = parseJson['tick'] as Map<String, dynamic>;
      final List<DepthEntity> bids = (tick['bids'] as List<dynamic>)
          .map<DepthEntity>(
              (item) => DepthEntity(item[0] as double, item[1] as double))
          .toList();
      final List<DepthEntity> asks = (tick['asks'] as List<dynamic>)
          .map<DepthEntity>(
              (item) => DepthEntity(item[0] as double, item[1] as double))
          .toList();
      initDepth(bids, asks);
    });
  }

  void initDepth(List<DepthEntity>? bids, List<DepthEntity>? asks) {
    if (bids == null || asks == null || bids.isEmpty || asks.isEmpty) return;
    _bids = [];
    _asks = [];
    double amount = 0.0;
    bids.sort((left, right) => left.price.compareTo(right.price));
    // 累加买入委托量
    bids.reversed.forEach((item) {
      amount += item.vol;
      item.vol = amount;
      _bids!.insert(0, item);
    });

    amount = 0.0;
    asks.sort((left, right) => left.price.compareTo(right.price));
    // 累加卖出委托量
    asks.forEach((item) {
      amount += item.vol;
      item.vol = amount;
      _asks!.add(item);
    });
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return ListView(
      shrinkWrap: true,
      children: <Widget>[
        Stack(children: <Widget>[
          Container(
            height: 450,
            width: double.infinity,
            child: KChartWidget(
              datas,
              chartStyle,
              chartColors,
              isLine: isLine,
              onSecondaryTap: () {
                print('Secondary Tap');
              },
              isTrendLine: _isTrendLine,
              mainState: _mainState,
              volHidden: _volHidden,
              secondaryState: _secondaryState,
              fixedLength: 2,
              timeFormat: TimeFormat.YEAR_MONTH_DAY,
              translations: kChartTranslations,
              showNowPrice: _showNowPrice,
              // `isChinese` 已弃用,使用 `translations` 替代
              isChinese: isChinese,
              hideGrid: _hideGrid,
              isTapShowInfoDialog: false,
              verticalTextAlignment: _verticalTextAlignment,
              maDayList: [1, 100, 1000],
            ),
          ),
          if (showLoading)
            Container(
                width: double.infinity,
                height: 450,
                alignment: Alignment.center,
                child: const CircularProgressIndicator()),
        ]),
        buildButtons(),
        if (_bids != null && _asks != null)
          Container(
            height: 230,
            width: double.infinity,
            child: DepthChart(_bids!, _asks!, chartColors),
          )
      ],
    );
  }

  Widget buildButtons() {
    return Wrap(
      alignment: WrapAlignment.spaceEvenly,
      children: <Widget>[
        button("时间模式", onPressed: () => isLine = true),
        button("K线模式", onPressed: () => isLine = false),
        button("趋势线", onPressed: () => _isTrendLine = !_isTrendLine),
        button("主图:MA", onPressed: () => _mainState = MainState.MA),
        button("主图:BOLL", onPressed: () => _mainState = MainState.BOLL),
        button("隐藏主图", onPressed: () => _mainState = MainState.NONE),
        button("副图:MACD", onPressed: () => _secondaryState = SecondaryState.MACD),
        button("副图:KDJ", onPressed: () => _secondaryState = SecondaryState.KDJ),
        button("副图:RSI", onPressed: () => _secondaryState = SecondaryState.RSI),
        button("副图:WR", onPressed: () => _secondaryState = SecondaryState.WR),
        button("副图:CCI", onPressed: () => _secondaryState = SecondaryState.CCI),
        button("副图:隐藏", onPressed: () => _secondaryState = SecondaryState.NONE),
        button(_volHidden ? "显示成交量" : "隐藏成交量", onPressed: () => _volHidden = !_volHidden),
        button("切换语言", onPressed: () => isChinese = !isChinese),
        button(_hideGrid ? "显示网格" : "隐藏网格", onPressed: () => _hideGrid = !_hideGrid),
        button(_showNowPrice ? "隐藏当前价格" : "显示当前价格", onPressed: () => _showNowPrice = !_showNowPrice),
        button("自定义UI", onPressed: () {
          setState(() {
            this.isChangeUI = !this.isChangeUI;
            if (this.isChangeUI) {
              chartColors.selectBorderColor = Colors.red;
              chartColors.selectFillColor = Colors.red;
              chartColors.lineFillColor = Colors.red;
              chartColors.kLineColor = Colors.yellow;
            } else {
              chartColors.selectBorderColor = Color(0xff6C7A86);
              chartColors.selectFillColor = Color(0xff0D1722);
              chartColors.lineFillColor = Color(0x554C86CD);
              chartColors.kLineColor = Color(0xff4C86CD);
            }
          });
        }),
        button("切换价格文本对齐方式", onPressed: () => setState(() {
          _priceLeft = !_priceLeft;
          if (_priceLeft) {
            _verticalTextAlignment = VerticalTextAlignment.left;
          } else {
            _verticalTextAlignment = VerticalTextAlignment.right;
          }
        })),
      ],
    );
  }

  Widget button(String text, {VoidCallback? onPressed}) {
    return TextButton(
      onPressed: () {
        if (onPressed != null) {
          onPressed();
          setState(() {});
        }
      },
      child: Text(text),
      style: TextButton.styleFrom(
        primary: Colors.white,
        minimumSize: const Size(88, 44),
        padding: const EdgeInsets.symmetric(horizontal: 16.0),
        shape: const RoundedRectangleBorder(
          borderRadius: BorderRadius.all(Radius.circular(2.0)),
        ),
        backgroundColor: Colors.blue,
      ),
    );
  }

  void getData(String period) {
    /*
     * 可以翻墙使用方法1加载数据,不可以翻墙使用方法2加载数据,默认使用方法1加载最新数据
     */
    final Future<String> future = getChatDataFromInternet(period);
    // final Future<String> future = getChatDataFromJson();
    future.then((String result) {
      solveChatData(result);
    }).catchError((_) {
      showLoading = false;
      setState(() {});
      print('### datas error $_');
    });
  }

  // 获取火币数据,需要翻墙
  Future<String> getChatDataFromInternet(String? period) async {
    var url = 'https://api.huobi.br.com/market/history/kline?period=${period ?? '1day'}&size=300&symbol=btcusdt';
    late String result;
    final response = await http.get(Uri.parse(url));
    if (response.statusCode == 200) {
      result = response.body;
    } else {
      print('Failed getting IP address');
    }
    return result;
  }

  // 如果你不能翻墙,可以使用这个方法加载数据
  Future<String> getChatDataFromJson() async {
    return rootBundle.loadString('assets/chatData.json');
  }

  void solveChatData(String result) {
    final Map parseJson = json.decode(result) as Map<dynamic, dynamic>;
    final list = parseJson['data'] as List<dynamic>;
    datas = list
        .map((item) => KLineEntity.fromJson(item as Map<String, dynamic>))
        .toList()
        .reversed
        .toList()
        .cast<KLineEntity>();
    DataUtil.calculate(datas!);
    showLoading = false;
    setState(() {});
  }
}

以上代码展示了如何使用k_chart插件来绘制K线图和深度图,并提供了多种配置选项。希望对你有所帮助!


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

1 回复

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


当然,下面是一个关于如何在Flutter中使用k_chart插件来绘制图表的示例代码。k_chart是一个用于绘制金融图表的Flutter插件,尽管具体细节可能会因插件版本和API更新而有所变化,但以下代码提供了一个基本的使用示例。

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

dependencies:
  flutter:
    sdk: flutter
  k_chart: ^最新版本号  # 替换为实际最新版本号

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

接下来,在你的Flutter项目中,你可以按照以下方式使用k_chart来绘制一个简单的图表:

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

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

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

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  // 模拟一些数据
  List<KLineEntity> getKLineData() {
    return [
      KLineEntity(
        dateTime: DateTime.now().subtract(Duration(days: 9)),
        open: 100,
        high: 110,
        low: 90,
        close: 105,
        volume: 1000,
      ),
      KLineEntity(
        dateTime: DateTime.now().subtract(Duration(days: 8)),
        open: 105,
        high: 120,
        low: 95,
        close: 115,
        volume: 1500,
      ),
      // ... 添加更多数据点
    ];
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('k_chart Demo'),
      ),
      body: Center(
        child: Container(
          height: 400,
          child: KChart(
            kLineDataList: getKLineData(),
            mainLineColor: Colors.blue,
            gridColor: Colors.grey[300]!,
            gridLineWidth: 0.5,
            crossHairColor: Colors.red,
            crossHairLineWidth: 1.0,
            maxValue: 150,
            minValue: 50,
            title: Text('K线图表'),
            showVolume: true,
          ),
        ),
      ),
    );
  }
}

// KLineEntity 是一个示例数据模型,你需要根据 k_chart 插件的实际要求来定义它
class KLineEntity {
  DateTime dateTime;
  double open;
  double high;
  double low;
  double close;
  int volume;

  KLineEntity({
    required this.dateTime,
    required this.open,
    required this.high,
    required this.low,
    required this.close,
    required this.volume,
  });
}

注意

  1. KLineEntity类是一个示例数据模型,你需要根据k_chart插件的实际API和数据结构来定义它。
  2. 插件的API和数据结构可能会随着版本更新而变化,所以请务必查阅最新的k_chart文档以获取准确的信息。
  3. 如果k_chart插件有特定的初始化或配置要求(如主题、样式等),请确保在代码中正确实现。

以上代码提供了一个基本的框架,展示了如何在Flutter应用中使用k_chart插件来绘制金融图表。你可以根据实际需求进一步定制和扩展。

回到顶部