Flutter K线图绘制插件kline_chart的使用

Flutter K线图绘制插件kline_chart的使用

flutter kline chart插件

Demo Gif

使用

import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:kline_chart/kline_chart.dart';

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

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

  [@override](/user/override)
  Widget build(BuildContext context) {
    return const MaterialApp(title: "flutter kline demo app", home: MyHomePage(title: 'flutter kline demo'));
  }
}

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

  final String title;

  [@override](/user/override)
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  List<String> mainIndicators = KLineController.shared.showMainIndicators.map((e) => e.name).toList();
  List<String> subIndicators = KLineController.shared.showSubIndicators.map((e) => e.name).toList();

  bool _showTimeChart = false;

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

    _loadJson().then((value) {
      KLineController.shared.data = value;
      setState(() {});
    });
  }

  Widget buildIndicator(String name, bool isMain, void Function(String, bool) click) {
    Color c = (isMain ? mainIndicators.contains(name) : subIndicators.contains(name)) ? Colors.blue : Colors.grey;
    return InkWell(
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 8),
        child: Text(name, style: TextStyle(fontSize: 14, color: c)),
      ),
      onTap: () => click(name, isMain),
    );
  }

  void clickIndicator(name, isMain) {
    if (isMain) {
      if (mainIndicators.contains(name)) {
        mainIndicators.remove(name);
      } else {
        if (mainIndicators.isNotEmpty) mainIndicators.removeAt(0);
        mainIndicators.add(name);
      }

      KLineController.shared.showMainIndicators = mainIndicators.map((e) => IndicatorType.fromName(e)).toList();
    } else {
      if (subIndicators.contains(name)) {
        subIndicators.remove(name);
      } else if (subIndicators.length == 2) {
        if (subIndicators.isNotEmpty) subIndicators.removeAt(0);
        subIndicators.add(name);
      } else {
        subIndicators.add(name);
      }
      KLineController.shared.showSubIndicators = subIndicators.map((e) => IndicatorType.fromName(e)).toList();
    }
    setState(() {});
  }

  Future<List<KLineData>> _loadJson() async {
    final jsonStr = await rootBundle.loadString('lib/kline.json');
    List jsonList = json.decode(jsonStr);
    List<KLineData> dataList = [];
    for (var data in jsonList) {
      var klineData = KLineData()
        ..open = double.parse(data[1] ?? '0')
        ..high = double.parse(data[2] ?? '0')
        ..low = double.parse(data[3] ?? '0')
        ..close = double.parse(data[4] ?? '0')
        ..volume = double.parse(data[5] ?? '0')
        ..time = data[6] ?? 0;

      dataList.add(klineData);
    }
    return dataList;
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(widget.title),
        ),
        body: Center(
            child: Column(
          children: [
            Container(
                height: 50,
                padding: const EdgeInsets.symmetric(horizontal: 20),
                child: Row(children: [
                  const Text("Main Indicator"),
                  ...IndicatorType.values.where((element) => element.isMain).map((e) {
                    return buildIndicator(e.name, e.isMain, clickIndicator);
                  })
                ])),
            Container(
                height: 50,
                padding: const EdgeInsets.symmetric(horizontal: 20),
                child: Row(children: [
                  const Text("Sub Indicator"),
                  ...IndicatorType.values.where((element) => !element.isMain && element != IndicatorType.maVol).map((e) {
                    return buildIndicator(e.name, e.isMain, clickIndicator);
                  })
                ])),
            Container(
              alignment: Alignment.centerLeft,
              height: 50,
              padding: const EdgeInsets.symmetric(horizontal: 20),
              child: InkWell(
                onTap: () => setState(() {
                  _showTimeChart = !_showTimeChart;
                  KLineController.shared.showTimeChart = _showTimeChart;
                }),
                child: Text('Time', style: TextStyle(
                  color: _showTimeChart ? Colors.blue : Colors.grey
                ),),
              )
            ),
            Container(
                width: MediaQuery.of(context).size.width,
                height: 400,
                decoration: const BoxDecoration(border: Border.symmetric(horizontal: BorderSide(color: Colors.black))),
                child: KLineView())
          ],
        )) // This trailing comma makes auto-formatting nicer for build methods.
        );
  }
}

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

1 回复

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


kline_chart 是一个用于在 Flutter 应用中绘制 K 线图的插件。它可以帮助你快速实现股票、加密货币等金融数据的 K 线图展示。以下是使用 kline_chart 插件的基本步骤:

1. 添加依赖

首先,你需要在 pubspec.yaml 文件中添加 kline_chart 插件的依赖:

dependencies:
  flutter:
    sdk: flutter
  kline_chart: ^0.1.0  # 请检查最新版本

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

2. 导入插件

在你的 Dart 文件中导入 kline_chart 插件:

import 'package:kline_chart/kline_chart.dart';

3. 准备数据

kline_chart 插件需要特定的数据结构来绘制 K 线图。通常,你需要准备一个包含 K 线数据的列表,每个 K 线数据项包含开盘价、收盘价、最高价、最低价等信息。

List<KLineEntity> kLineData = [
  KLineEntity(
    open: 100.0,
    close: 105.0,
    high: 110.0,
    low: 95.0,
    vol: 1000.0,
    date: DateTime(2023, 10, 1),
  ),
  KLineEntity(
    open: 105.0,
    close: 102.0,
    high: 108.0,
    low: 100.0,
    vol: 800.0,
    date: DateTime(2023, 10, 2),
  ),
  // 添加更多 K 线数据
];

4. 使用 KLineChart 组件

在你的 Flutter 页面中,使用 KLineChart 组件来展示 K 线图:

class KLineChartPage extends StatelessWidget {
  final List<KLineEntity> kLineData;

  KLineChartPage({required this.kLineData});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('KLine Chart'),
      ),
      body: KLineChart(
        data: kLineData,
        isLine: false, // 是否显示折线图,默认为 K 线图
        mainState: MainState.MA, // 主图指标,例如 MA
        secondaryState: SecondaryState.MACD, // 副图指标,例如 MACD
        onLoadMore: (bool isLoadMore) {
          // 加载更多数据的回调
        },
      ),
    );
  }
}

5. 运行应用

现在你可以运行你的 Flutter 应用,查看 K 线图的效果。

6. 自定义配置

kline_chart 插件提供了多种配置选项,你可以根据需要自定义 K 线图的样式、指标、交互等。

KLineChart(
  data: kLineData,
  isLine: false,
  mainState: MainState.MA,
  secondaryState: SecondaryState.MACD,
  onLoadMore: (bool isLoadMore) {
    // 加载更多数据的回调
  },
  theme: KLineChartTheme(
    // 自定义主题
    primaryColor: Colors.blue,
    secondaryColor: Colors.green,
    // 其他样式配置
  ),
  // 其他配置项
);

7. 处理交互

kline_chart 插件支持用户交互,例如缩放、拖动、点击等。你可以通过回调函数来处理这些交互事件。

KLineChart(
  data: kLineData,
  onScale: (double scale) {
    // 处理缩放事件
  },
  onDrag: (double offset) {
    // 处理拖动事件
  },
  onTap: (KLineEntity entity) {
    // 处理点击事件
  },
);
回到顶部