Flutter图表绘制插件charts_flutter_maintained的使用

Flutter图表绘制插件charts_flutter_maintained的使用

Flutter图表库

pub package

Material Design数据可视化库,用Dart语言原生编写。

支持的图表

查看在线画廊

使用库

charts_flutter项目中的/example/文件夹包含一个完整的Flutter应用程序,其中有许多演示示例。

开发

该项目在Google内部开发,并发布供外部使用。欢迎对本包感兴趣的人参与贡献!


完整示例Demo

以下是一个完整的Flutter应用示例,展示了如何使用charts_flutter_maintained插件来绘制图表。

// Copyright 2018 the Charts project authors. Please see the AUTHORS file
// for details.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

import 'package:flutter/material.dart';

/// 主图库应用小部件。
class GalleryApp extends StatefulWidget {
  GalleryApp({Key? key}) : super(key: key);

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

/// 主图库应用状态。
///
/// 控制性能覆盖,并实例化一个Home小部件。
class GalleryAppState extends State<GalleryApp> {
  // 初始化应用设置。
  bool _showPerformanceOverlay = false;

  [@override](/user/override)
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Charts Flutter Maintained Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      showPerformanceOverlay: _showPerformanceOverlay,
      home: Home(
        showPerformanceOverlay: _showPerformanceOverlay,
        onShowPerformanceOverlayChanged: (bool value) {
          setState(() {
            _showPerformanceOverlay = value;
          });
        },
      ),
    );
  }
}

void main() {
  runApp(new GalleryApp());
}

/// 主页小部件。
class Home extends StatelessWidget {
  final bool showPerformanceOverlay;
  final Function(bool) onShowPerformanceOverlayChanged;

  Home({
    required this.showPerformanceOverlay,
    required this.onShowPerformanceOverlayChanged,
  });

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Charts Flutter Maintained Demo'),
        actions: [
          Switch(
            value: showPerformanceOverlay,
            onChanged: (value) {
              onShowPerformanceOverlayChanged(value);
            },
          ),
        ],
      ),
      body: Center(
        child: SimpleLineChart.withSampleData(),
      ),
    );
  }
}

/// 简单折线图。
class SimpleLineChart extends StatelessWidget {
  final List<Series<dynamic, num>> seriesList;
  final bool animate;

  SimpleLineChart(this.seriesList, {this.animate});

  factory SimpleLineChart.withSampleData() {
    return new SimpleLineChart(
      _createSampleData(),
      animate: true,
    );
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return new charts.LineChart(
      seriesList,
      animate: animate,
      behaviors: [
        new charts.ChartTitle(
          'Time',
          behaviorPosition: charts.BehaviorPosition.bottom,
          titleOutsideJustification:
              charts.OutsideJustification.middleDrawArea,
        ),
        new charts.ChartTitle(
          'Sales',
          behaviorPosition: charts.BehaviorPosition.start,
          titleOutsideJustification:
              charts.OutsideJustification.middleDrawArea,
        ),
      ],
    );
  }

  /// Create one series with sample hard coded data.
  static List<Series<LinearSales, int>> _createSampleData() {
    final data = [
      LinearSales(0, 5),
      LinearSales(1, 25),
      LinearSales(2, 100),
      LinearSales(3, 75),
    ];

    return [
      new Series<LinearSales, int>(
        id: 'Sales',
        domainFn: (LinearSales sales, _) => sales.year,
        measureFn: (LinearSales sales, _) => sales.sales,
        data: data,
      )
    ];
  }
}

/// 线性销售数据类。
class LinearSales {
  final int year;
  final int sales;

  LinearSales(this.year, this.sales);
}

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

1 回复

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


当然,下面是一个关于如何使用 charts_flutter_maintained 插件在 Flutter 中绘制图表的示例代码。这个插件是 Google 官方维护的 Flutter 图表库之一,提供了多种类型的图表,包括柱状图、折线图、饼图等。

首先,确保在你的 pubspec.yaml 文件中添加依赖:

dependencies:
  flutter:
    sdk: flutter
  charts_flutter_maintained: ^0.14.0  # 请检查最新版本号

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

接下来是一个简单的示例,展示如何使用 charts_flutter_maintained 绘制一个柱状图(Bar Chart)。

import 'package:flutter/material.dart';
import 'package:charts_flutter_maintained/flutter.dart' as charts;

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

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

class MyHomePage extends StatelessWidget {
  final List<charts.Series<BarChartData, String>> _seriesList;
  final bool animate;

  MyHomePage({Key key, this.animate})
      : _seriesList = _createSampleData(),
        super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Bar Chart Demo'),
      ),
      body: Center(
        child: charts.BarChart(
          _seriesList,
          animate: animate,
        ),
      ),
    );
  }

  List<charts.Series<BarChartData, String>> _createSampleData() {
    final data = [
      BarChartData('2023', 5),
      BarChartData('2024', 15),
      BarChartData('2025', 25),
      BarChartData('2026', 35),
      BarChartData('2027', 45),
    ];

    return [
      charts.Series<BarChartData, String>(
        id: 'Sales',
        data: data,
        domainFn: (BarChartData sales, _) => sales.year,
        measureFn: (BarChartData sales, _) => sales.sales,
        colorFn: (_, __) => charts.MaterialPalette.blue.shadeDefault,
      ),
    ];
  }
}

class BarChartData {
  final String year;
  final int sales;

  BarChartData(this.year, this.sales);
}

在这个示例中:

  1. 我们定义了一个 BarChartData 类来存储柱状图的数据,包括年份和销售数据。
  2. MyHomePage 类中,我们创建了一个包含样本数据的 _seriesList 列表。
  3. 使用 charts.Series 类来定义图表系列,包括数据的标识符、数据列表、用于确定 X 轴值的函数(domainFn)、用于确定 Y 轴值的函数(measureFn)以及颜色函数(colorFn)。
  4. 最后,我们在 Scaffoldbody 中使用 charts.BarChart 小部件来渲染柱状图。

你可以根据需要调整数据、样式和功能,以满足你的特定需求。charts_flutter_maintained 插件提供了丰富的自定义选项,可以让你创建各种复杂和美观的图表。

回到顶部