Flutter 圖表繪製解密(charts_flutter 的使用)

Flutter程式設計開發發表於2020-03-29

原文連結 : Flutter — Charts and Graphs demystified

一、圖表的作用

統計學在我們的日常生活扮演著一個重要的角色,因為它可以幫助我們理解人類生存所必需的資料。 資料視覺化非常重要,資料的視覺化可以幫助我們更直觀的理解資料。視覺化就是資料的繪製過程,包括繪製各種曲線(curves)/圖表(charts)/圖形(graphs)/平面圖(plots)以使資料易於理解。

Flutter 圖表繪製解密(charts_flutter 的使用)

圖表是許多應用程式的主要組成部分之一。許多應用程式(例如Medium,StackOverflow,GitHub等)都在大量應用程式中使用圖形和圖表。直接看原始資料使人非常失望沮喪。因此,在應用程式中使用圖片,圖形和圖表可以讓我們操作的資料更加直觀。

一圖勝千言

Flutter 圖表繪製解密(charts_flutter 的使用)

易卜生(Henrik Ibsen)說得好,因為我們的人性使我們更容易被圖形和圖表吸引,而不是原始文字。如果直接以行或者列的方式展示資料,則可能無法輕鬆獲得資料的關係,資料間的依賴關係和資料趨勢,如果基於資料繪製圖表,這些可能更輕鬆的理解。

Flutter 是一個現代化的 UI 框架,為我們提供了非常多優雅使用圖表和圖形的選擇。使用 Flutter 的原始效能,可以使繪製的 Graphs 和 Charts 有非常好的使用者體驗。要在 Flutter中使用圖表,可能有很多種方式,但是在本文中,我們將重點介紹其中一些。

Flutter框架(更準確地說是pub.dev)包含一個名為 Charts_flutter 的程式包,它為使用Flutter中的圖表提供了非常龐大而優雅的工具包。該軟體包為我們提供了許多繪製不同型別的圖和圖表的選項。接下來基於這個包來展示圖形和圖示的繪製。

Flutter 圖表繪製解密(charts_flutter 的使用)

二、基於 charts_flutter 進行圖形繪製

首先,再使用之前,需要在 pubspec.yaml 檔案中新增 Charts_flutter 依賴。

現在,在完成依賴項設定後,我們將繪製不同型別的圖表

1、條形圖繪製

步驟1:準備資料

在繪製條形圖之前,我們將首先準備資料。為此,我們以最近幾年的美國人口資料繪製為例,先定義一個PopulationData類。

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

class PopulationData {
  int year;
  int population;
  charts.Color barColor;
  PopulationData({
    @required this.year, 
    @required this.population,
    @required this.barColor
  });
}
複製程式碼

接下來為繪製的圖形準備一些假資料,並將其繪製在條形圖中

final List<PopulationData> data = [
    PopulationData(
      year: 1880,
      population: 50189209,
      barColor: charts.ColorUtil.fromDartColor(Colors.lightBlue)
    ),
    PopulationData(
      year: 1890,
      population: 62979766,
      barColor: charts.ColorUtil.fromDartColor(Colors.lightBlue)
    ),
    PopulationData(
      year: 1900,
      population: 76212168,
      barColor: charts.ColorUtil.fromDartColor(Colors.lightBlue)
    ),
    PopulationData(
      year: 1910,
      population: 92228496,
      barColor: charts.ColorUtil.fromDartColor(Colors.lightBlue)
    ),
    PopulationData(
      year: 1920,
      population: 106021537,
      barColor: charts.ColorUtil.fromDartColor(Colors.blue)
    ),
    PopulationData(
      year: 1930,
      population: 123202624,
      barColor: charts.ColorUtil.fromDartColor(Colors.blue)
    ),
    PopulationData(
      year: 1940,
      population: 132164569,
      barColor: charts.ColorUtil.fromDartColor(Colors.blue)
    ),
    PopulationData(
      year: 1950,
      population: 151325798,
      barColor: charts.ColorUtil.fromDartColor(Colors.blue)
    ),
    PopulationData(
      year: 1960,
      population: 179323175,
      barColor: charts.ColorUtil.fromDartColor(Colors.blue)
    ),
    PopulationData(
      year: 1970,
      population: 203302031,
      barColor: charts.ColorUtil.fromDartColor(Colors.purple)
    ),
    PopulationData(
      year: 1980,
      population: 226542199,
      barColor: charts.ColorUtil.fromDartColor(Colors.purple)
    ),
    PopulationData(
      year: 1990,
      population: 248709873,
      barColor: charts.ColorUtil.fromDartColor(Colors.purple)
    ),
    PopulationData(
      year: 2000,
      population: 281421906,
      barColor: charts.ColorUtil.fromDartColor(Colors.purple)
    ),
    PopulationData(
      year: 2010,
      population: 307745538,
      barColor: charts.ColorUtil.fromDartColor(Colors.black)
    ),
    PopulationData(
      year: 2017,
      population: 323148586,
      barColor: charts.ColorUtil.fromDartColor(Colors.black)
    ),
    
  ];
複製程式碼

第2步:定義UI

準備好要繪製的資料後,接下來定義需要展示資料的 UI。

@override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Bar Chart Example'), centerTitle: true,),
      body: Center(
      child: Container(
          height: 400,
          padding: EdgeInsets.all(20),
          child: Card(
            child: Padding(
              padding: const EdgeInsets.all(8.0),
              child: Column(
                children: <Widget>[
                  Text(
                    "Population of U.S. over the years",
                    style: TextStyle(
                      fontWeight: FontWeight.bold
                    ),
                  ),
                  SizedBox(height: 20,),
                  Expanded(
                    child: charts.BarChart(
                      _getSeriesData(), 
                      animate: true,
                      domainAxis: charts.OrdinalAxisSpec(
                        renderSpec: charts.SmallTickRendererSpec(labelRotation: 60)
                      ),
                    ),
                  )
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }
複製程式碼

在上面的程式碼中,我們使用BarChart()小部件來繪製條形圖,BarChart 這個 Widget 有很多編輯圖的選項,在上面的示例中,我們旋轉了 x 軸標籤,不旋轉的話會有重疊。這個 Widget 還有其他的屬性,可以在圖表中完成其他的圖形操作 。上面程式碼裡面使用到的 _getSeriesData() 函式定義如下:

_getSeriesData() {
    List<charts.Series<PopulationData, String>> series = [
      charts.Series(
        id: "Population",
        data: data,
        domainFn: (PopulationData series, _) => series.year.toString(),
        measureFn: (PopulationData series, _) => series.population,
        colorFn: (PopulationData series, _) => series.barColor
      )
    ];
    return series;
}
複製程式碼

結果:

Flutter 圖表繪製解密(charts_flutter 的使用)

2、繪製線形圖

第1步:定義資料

在繪製折線圖之前,我們將首先準備要處理的資料。以公司的銷售資料為例,先準備一個 SalesData類。

class SalesData {
  final int year;
  final int sales;

  SalesData(this.year, this.sales);
}
複製程式碼

接著準備一些繪製時用的假資料。

final data = [
    new SalesData(0, 1500000),
    new SalesData(1, 1735000),
    new SalesData(2, 1678000),
    new SalesData(3, 1890000),
    new SalesData(4, 1907000),
    new SalesData(5, 2300000),
    new SalesData(6, 2360000),
    new SalesData(7, 1980000),
    new SalesData(8, 2654000),
    new SalesData(9, 2789070),
    new SalesData(10, 3020000),
    new SalesData(11, 3245900),
    new SalesData(12, 4098500),
    new SalesData(13, 4500000),
    new SalesData(14, 4456500),
    new SalesData(15, 3900500),
    new SalesData(16, 5123400),
    new SalesData(17, 5589000),
    new SalesData(18, 5940000),
    new SalesData(19, 6367000),
 ];

_getSeriesData() {
    List<charts.Series<SalesData, int>> series = [
      charts.Series(
        id: "Sales",
        data: data,
        domainFn: (SalesData series, _) => series.year,
        measureFn: (SalesData series, _) => series.sales,
        colorFn: (SalesData series, _) => charts.MaterialPalette.blue.shadeDefault
      )
    ];
    return series;
}
複製程式碼

步驟2:定義UI

接下來使用 charts_flutter 包裡面的 LineChart 來展示圖表。

Expanded(
  child: new charts.LineChart(_getSeriesData(), animate: true,),
)
複製程式碼

結果:

Flutter 圖表繪製解密(charts_flutter 的使用)

3、繪製餅狀圖

步驟1:定義資料

以繪製學校裡面的學生的成績為例,先定義一個 GradesData 類。

class GradesData {
  final String gradeSymbol;
  final int numberOfStudents;

  GradesData(this.gradeSymbol, this.numberOfStudents);
}
複製程式碼

接下來準備一些繪製用的假資料:


final data = [
  GradesData('A', 190),
  GradesData('B', 230),
  GradesData('C', 150),
  GradesData('D', 73),
  GradesData('E', 31),
  GradesData('Fail', 13),
];

_getSeriesData() {
  List<charts.Series<GradesData, String>> series = [
    charts.Series(
      id: "Grades",
      data: data,
      labelAccessorFn: (GradesData row, _) => '${row.gradeSymbol}: ${row.numberOfStudents}',
      domainFn: (GradesData grades, _) => grades.gradeSymbol,
      measureFn: (GradesData grades, _) => grades.numberOfStudents
    )
  ];
  return series;
}
複製程式碼

步驟2:定義UI

接下來使用 charts_flutter 裡面的 PieChart 來繪製餅狀圖。

Expanded(
  child: new charts.PieChart(
    _getSeriesData(),
    animate: true,
    defaultRenderer: new charts.ArcRendererConfig(
      arcWidth: 60,
      arcRendererDecorators: [new charts.ArcLabelDecorator()]
    ),
  ),
)
複製程式碼

結果:

Flutter 圖表繪製解密(charts_flutter 的使用)

完整示例:

Flutter 圖表繪製解密(charts_flutter 的使用)

github

最後

歡迎關注「Flutter 程式設計開發」微信公眾號 。

Flutter 圖表繪製解密(charts_flutter 的使用)

相關文章