Flutter图表绘制插件k_chart_flutter的使用

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

Flutter图表绘制插件k_chart_flutter的使用

1. 插件简介

k_chart_flutter 是一个用于在Flutter中绘制K线图的插件,支持多种手势操作和常见的技术指标。以下是该插件的主要功能:

  • 手势支持:支持拖动、缩放、长按、快速滑动等手势。
  • 主图指标:支持移动平均线(MA)和布林带(BOLL)。
  • 副图指标:支持MACD、KDJ、RSI、WR、CCI等技术指标。

2. 安装

pubspec.yaml 文件中添加依赖:

dependencies:
  k_chart_flutter: ^1.0.0

3. 使用示例

以下是一个完整的示例代码,展示了如何使用 k_chart_flutter 插件来绘制K线图,并提供了切换不同图表模式、显示/隐藏成交量、切换语言等功能。

示例代码
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:http/http.dart' as http;
import 'package:k_chart_flutter/chart_translations.dart';
import 'package:k_chart_flutter/k_chart_flutter.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(primarySwatch: Colors.green),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, this.title}) : super(key: key);

  final String? title;

  [@override](/user/override)
  MyHomePageState createState() => MyHomePageState();
}

class MyHomePageState extends State<MyHomePage> {
  List<KLineEntity>? data;
  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;

  ChartStyle chartStyle = ChartStyle(
    select: const ChartSelectStyle(y: ChartCrossLineStyle(color: Colors.red, length: 20)),
  );

  [@override](/user/override)
  void initState() {
    super.initState();
    _init();
  }

  Future<void> _init() async {
    // 获取K线数据
    getData('1day');

    // 加载深度数据
    final result = await rootBundle.loadString('assets/depth.json');
    final parseJson = json.decode(result);
    final tick = parseJson['tick'] as Map<String, dynamic>;

    final List<DepthEntity> bids = (tick['bids'] as List<dynamic>)
        .map((item) => DepthEntity(item[0] as double, item[1] as double))
        .toList();
    final List<DepthEntity> asks = (tick['asks'] as List<dynamic>)
        .map((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));
    // 累加买入委托量
    for (var item in bids.reversed) {
      amount += item.vol;
      item.vol = amount;
      _bids!.insert(0, item);
    }

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

  [@override](/user/override)
  Widget build(BuildContext context) {
    return ListView(
      shrinkWrap: true,
      children: [
        Stack(
          children: [
            SizedBox(
              height: 450,
              width: double.infinity,
              child: KChartWidget(
                data: data,
                style: chartStyle,
                isLine: isLine,
                isTrendLine: _isTrendLine,
                mainState: _mainState,
                volHidden: _volHidden,
                secondaryState: _secondaryState,
                timeFormat: TimeFormat.YEAR_MONTH_DAY,
                translations: kChartTranslations,
                showNowPrice: _showNowPrice,
                hideGrid: _hideGrid,
                isTapShowInfoDialog: true,
                maDayList: const [1, 100, 1000],
                dataFormat: (value) => value.toStringAsFixed(2),
              ),
            ),
            if (showLoading)
              Container(
                width: double.infinity,
                height: 450,
                alignment: Alignment.center,
                child: const CircularProgressIndicator(),
              ),
          ],
        ),
        buildButtons(),
        if (_bids != null && _asks != null)
          SizedBox(
            height: 230,
            width: double.infinity,
            child: DepthChart(
              bids: _bids!,
              asks: _asks!,
              colors: const DepthColors(),
            ),
          ),
      ],
    );
  }

  Widget buildButtons() {
    return Wrap(
      alignment: WrapAlignment.spaceEvenly,
      children: [
        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),
      ],
    );
  }

  Widget button(String text, {VoidCallback? onPressed}) {
    return TextButton(
      onPressed: () {
        if (onPressed != null) {
          onPressed();
          setState(() {});
        }
      },
      style: TextButton.styleFrom(
        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,
      ),
      child: Text(text, style: TextStyle(color: Colors.white)),
    );
  }

  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(() {});
    });
  }

  // 获取火币数据,需要翻墙
  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 {
      debugPrint('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>;
    data = list
        .map((item) => KLineEntity.fromJson(item as Map<String, dynamic>))
        .toList()
        .reversed
        .toList()
        .cast<KLineEntity>();

    DataUtil.calculate(data!);
    showLoading = false;
    setState(() {});
  }
}

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

1 回复

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


当然,以下是如何在Flutter项目中使用k_chart_flutter插件来绘制图表的示例代码。假设你已经在你的pubspec.yaml文件中添加了k_chart_flutter依赖,并且已经运行了flutter pub get命令。

首先,确保你的pubspec.yaml文件包含以下依赖:

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

然后,你可以按照以下步骤在你的Flutter应用中绘制图表。

1. 导入必要的包

在你的Dart文件中导入k_chart_flutter包:

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

2. 创建图表数据

接下来,你需要创建用于绘制图表的数据。这里以简单的折线图为例:

List<KLineEntity> _generateKLineData() {
  List<KLineEntity> data = [];
  for (int i = 0; i < 10; i++) {
    data.add(KLineEntity(
      dateTime: DateTime.now().subtract(Duration(days: i)),
      open: 100 + i * 2.0,
      high: 110 + i * 2.0,
      low: 90 + i * 2.0,
      close: 105 + i * 2.0,
      volume: 1000 + i * 10,
    ));
  }
  return data;
}

3. 构建图表

在你的Flutter组件中使用KChart小部件来绘制图表:

class MyChartScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    List<KLineEntity> data = _generateKLineData();

    return Scaffold(
      appBar: AppBar(
        title: Text('K-Chart Flutter Demo'),
      ),
      body: Center(
        child: Container(
          width: double.infinity,
          height: 400,
          child: KChart(
            data: data,
            chartType: KChartType.kLine, // 这里设置为K线图,你也可以选择其他类型,如柱状图等
            mainLineColor: Colors.blue,
            gridColor: Colors.grey[300]!,
            蜡烛图涨的颜色: Colors.green,
            蜡烛图跌的颜色: Colors.red,
            // 其他可配置的属性...
          ),
        ),
      ),
    );
  }
}

4. 运行应用

将上述代码添加到你的Flutter项目中,并确保你的主路由指向MyChartScreen

void main() {
  runApp(MaterialApp(
    home: MyChartScreen(),
  ));
}

现在,当你运行你的Flutter应用时,你应该能够看到一个包含K线图的屏幕。

注意事项

  • KLineEntityk_chart_flutter包中定义的数据模型,你需要根据你的实际数据格式进行相应的调整。
  • KChartType枚举定义了不同类型的图表,如K线图、柱状图等,你可以根据需要选择合适的图表类型。
  • k_chart_flutter插件提供了许多可配置的属性,如颜色、网格线、坐标轴等,你可以查阅官方文档以了解更多详细信息。

希望这能帮助你在Flutter项目中成功使用k_chart_flutter插件来绘制图表!

回到顶部