如何使用 charts_flutter 创建条形图

介绍

charts_flutter库是一个“用 Dart 原生编写的材料设计数据可视化库”。您可以在 Flutter 应用程序中使用此库将数据显示为条形图、折线图、散点图、饼图等。

在本文中,您将使用 2008 年到 2015 年之间的《魔兽世界》订阅者数量数据,并使用charts_flutter.

先决条件

要完成本教程,您需要:

本教程已通过 Flutter v1.22.2、Android SDK v31.0.2 和 Android Studio v4.1 验证。

步骤 1 — 设置项目

为 Flutter 设置环境后,您可以运行以下命令来创建新应用程序:

  • flutter create charts_flutter_example

导航到新的项目目录:

  • cd charts_flutter_example

使用flutter create将生成一个演示应用程序,该应用程序将显示单击按钮的次数。

第 2 步 – 添加charts_flutter插件

接下来,我们需要charts_flutter在我们插件中添加插件pubspec.yaml

pubspec.yaml
dependencies:
  flutter:
    sdk: flutter

  charts_flutter: ^0.10.0

我们现在可以继续在 iOS 或 Android 模拟器或您选择的设备上运行它。

第 3 步 – 搭建应用程序

现在,main.dart在您的代码编辑器中打开

将此文件中的所有内容替换为MaterialApp指向 a 的 aHomePage可在以下位置找到home.dart

lib/main.dart
import 'package:flutter/material.dart';
import 'package:charts_flutter_example/home.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: HomePage(),
    );
  }
}

接下来,创建一个新home.dart文件并添加以下代码行:

lib/home.dart
import 'package:flutter/material.dart';

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.red,
        title: Text("World of Warcraft Subscribers"),
      ),
      body: Center(
        child: Text("charts_flutter_example"),
      ),
    );
  }
}

现在我们已经建立了一个基础应用程序,我们可以继续为我们的条形图数据创建模型。

第 4 步 – 构建订阅者模型

我们的条形图将重点显示特定年份的《魔兽世界》订阅者数量。

接下来,创建一个新subscriber_series.dart文件并添加以下代码行:

lib/subscriber_series.dart
import 'package:flutter/foundation.dart';
import 'package:charts_flutter/flutter.dart' as charts;

class SubscriberSeries {
  final String year;
  final int subscribers;
  final charts.Color barColor;

  SubscriberSeries(
    {
      @required this.year,
      @required this.subscribers,
      @required this.barColor
    }
  );
}

这允许我们代表我们的数据yearsubscribers

第 5 步 – 创建数据

为了本教程,数据将在内部创建HomePageList<SubscriberSeries>

重新访问home.dart并添加以下代码行:

lib/home.dart
import 'package:flutter/material.dart';
import 'package:charts_flutter/flutter.dart' as charts;
import 'package:charts_flutter_example/subscriber_series.dart';

class HomePage extends StatelessWidget {
  final List<SubscriberSeries> data = [
    SubscriberSeries(
      year: "2008",
      subscribers: 10000000,
      barColor: charts.ColorUtil.fromDartColor(Colors.blue),
    ),
    SubscriberSeries(
      year: "2009",
      subscribers: 11000000,
      barColor: charts.ColorUtil.fromDartColor(Colors.blue),
    ),
    SubscriberSeries(
      year: "2010",
      subscribers: 12000000,
      barColor: charts.ColorUtil.fromDartColor(Colors.blue),
    ),
    SubscriberSeries(
      year: "2011",
      subscribers: 10000000,
      barColor: charts.ColorUtil.fromDartColor(Colors.blue),
    ),
    SubscriberSeries(
      year: "2012",
      subscribers: 8500000,
      barColor: charts.ColorUtil.fromDartColor(Colors.blue),
    ),
    SubscriberSeries(
      year: "2013",
      subscribers: 7700000,
      barColor: charts.ColorUtil.fromDartColor(Colors.blue),
    ),
    SubscriberSeries(
      year: "2014",
      subscribers: 7600000,
      barColor: charts.ColorUtil.fromDartColor(Colors.blue),
    ),
    SubscriberSeries(
      year: "2015",
      subscribers: 5500000,
      barColor: charts.ColorUtil.fromDartColor(Colors.red),
    ),
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.red,
        title: Text("World of Warcraft Subscribers"),
      ),
      body: Center(
        child: Text("charts_flutter_example"),
      ),
    );
  }
}

现在我们已经获得了数据,我们需要做的就是创建条形图!

步骤 6 — 创建条形图

现在,创建一个新subscriber_chart.dart文件并添加以下代码行:

lib/subscriber_chart.dart
import 'package:flutter/material.dart';
import 'package:charts_flutter/flutter.dart' as charts;
import 'package:charts_flutter_example/subscriber_series.dart';

class SubscriberChart extends StatelessWidget {
  final List<SubscriberSeries> data;

  SubscriberChart({@required this.data});
}

此代码创建一个新的StatelessWidget命名SubscriberChart在这需要SubscriberSeries作为prop

然后我们可以使用它data来构建我们的charts.Series像这样:

lib/subscriber_chart.dart
import 'package:flutter/material.dart';
import 'package:charts_flutter/flutter.dart' as charts;
import 'package:charts_flutter_example/subscriber_series.dart';

class SubscriberChart extends StatelessWidget {
  final List<SubscriberSeries> data;

  SubscriberChart({@required this.data});

  @override
  Widget build(BuildContext context) {
    List<charts.Series<SubscriberSeries, String>> series = [
      charts.Series(
        id: "Subscribers",
        data: data,
        domainFn: (SubscriberSeries series, _) => series.year,
        measureFn: (SubscriberSeries series, _) => series.subscribers,
        colorFn: (SubscriberSeries series, _) => series.barColor
      )
    ];
  }
}

domainFnmeasureFn被用来比较subscribers的数据year

我们还使用colorFn来潜在地传递barColor.

回想一下如何home.dart使用barColor

SubscriberSeries(
  year: "2008",
  subscribers: 10000000,
  barColor: charts.ColorUtil.fromDartColor(Colors.blue),
),

我们可能希望在生产应用程序中barColor使用默认值Colors.blue(或您选择的颜色)使可选项成为可选项在本教程中,一个条形将变为红色,其他条形将变为蓝色。

让我们更新build函数以返回我们的图表:

lib/subscriber_chart.dart
import 'package:flutter/material.dart';
import 'package:charts_flutter/flutter.dart' as charts;
import 'package:charts_flutter_example/subscriber_series.dart';

class SubscriberChart extends StatelessWidget {
  final List<SubscriberSeries> data;

  SubscriberChart({@required this.data});

  @override
  Widget build(BuildContext context) {
    List<charts.Series<SubscriberSeries, String>> series = [
      charts.Series(
        id: "Subscribers",
        data: data,
        domainFn: (SubscriberSeries series, _) => series.year,
        measureFn: (SubscriberSeries series, _) => series.subscribers,
        colorFn: (SubscriberSeries series, _) => series.barColor
      )
    ];

    return Container(
      height: 400,
      padding: EdgeInsets.all(20),
      child: Card(
        child: Padding(
          padding: const EdgeInsets.all(8.0),
          child: Column(
            children: <Widget>[
              Text(
                "World of Warcraft Subscribers by Year",
                style: Theme.of(context).textTheme.body2,
              ),
              Expanded(
                child: charts.BarChart(series, animate: true),
              )
            ],
          ),
        ),
      ),
    );
  }
}

此代码charts.BarChart通过用Card.

需要注意的关键是我们将series作为required参数传递charts.BarChart

charts.BarChart(series, animate: true)

此时,您的数据和图表就可以使用了。

步骤 7 — 显示图表

最后,home.dart在您的代码编辑器中重新访问并将 更改build为使用SubscriberChart

lib/home.dart
import 'package:flutter/material.dart';
import 'package:charts_flutter/flutter.dart' as charts;
import 'package:charts_flutter_example/subscriber_series.dart';
import 'package:charts_flutter_example/subscriber_chart.dart';

class HomePage extends StatelessWidget {
  // ...

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.red,
        title: Text("World of Warcraft Subscribers"),
      ),
      body: Center(
        child: SubscriberChart(
          data: data,
        )
      ),
    );
  }
}

保存更改并在模拟器中运行应用程序:

在 iOS 模拟器中运行的条形图的屏幕截图。

您的应用程序现在用于charts_flutter将数据显示为条形图。

结论

在本文中,您使用了 2008 年至 2015 年间魔兽世界订阅者数量的数据,并使用charts_flutter.

如果您想了解有关 Flutter 的更多信息,请查看我们的 Flutter 主题页面以获取练习和编程项目。

觉得文章有用?

点个广告表达一下你的爱意吧 !😁