Flutter — Charts and Graphs demystified

First, the role of charts

Statistics plays an important role in our daily life because it can help us understand the data necessary for human survival. Data visualization is very important. Data visualization can help us understand data more intuitively. Visualization is the process of plotting data, which involves drawing various curves/charts/graphs/plots to make the data easy to understand.

Charting is one of the main components of many applications. Many applications (for example Medium, StackOverflow, GitHub, etc.) use graphs and charts in a large number of applications. Looking directly at the raw data is very frustrating. Therefore, using pictures, graphs, and charts in the application makes the data we manipulate more intuitive.

A picture is worth a thousand words

Henrik Ibsen said it well, because our human nature makes us more attracted to graphs and charts than to raw text. If the data is presented directly in rows or columns, it may not be easy to obtain the relationships, dependencies between the data, and trends in the data, which may be easier to understand if you chart based on the data.

Flutter is a modern UI framework that gives us many options for using charts and graphics gracefully. Using the original performance of Flutter, Graphs and Charts can have a very good user experience. There are many ways to use charts in Flutter, but in this article we will highlight some of them.

The Flutter framework (more accurately pub.dev) contains a package called Charts_flutter, which provides a very large and elegant toolkit for working with charts in Flutter. The package gives us a number of options for plotting different types of graphs and charts. Next we show the drawing of graphics and ICONS based on this package.

2. Draw graphs based on Charts_FLUTTER

First, the Charts_flutter dependency needs to be added to the pubspec.yaml file before reuse.

Now, after completing the dependency setup, we will draw different types of diagrams

1. Bar chart drawing

Step 1: Prepare data

Before drawing the bar chart, we will first prepare the data. To this end, we take us PopulationData mapping in recent years as an example and define a PopulationData class first.

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
  });
}
Copy the code

Next prepare some fake data for the drawn graph and plot it in a bar chart

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)
    ),
    
  ];
Copy the code

Step 2: Define the UI

Now that you have the data to draw, you define the UI that you want to display the data to.

@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)),),)],),),),),),); }Copy the code

In the above code, we used the BarChart () Widget to draw the BarChart. The BarChart Widget has many options for editing the chart. In the above example, we rotated the X-axis label, otherwise there would be overlap. The Widget also has additional properties that allow you to perform other graphical operations within the diagram. The _getSeriesData() function used in the above code is defined as follows:

_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;
}
Copy the code

Results:

2. Draw line charts

Step 1: Define the data

Before drawing the line chart, we will first prepare the data to be processed. In the case of your company’s SalesData, prepare a SalesData class.

class SalesData {
  final int year;
  final int sales;

  SalesData(this.year, this.sales);
}
Copy the code

Then prepare some fake data for drawing.

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;
}
Copy the code

Step 2: Define the UI

Next use LineChart inside the Charts_flutter package to show the diagram.

Expanded(
  child: new charts.LineChart(_getSeriesData(), animate: true,),)Copy the code

Results:

3. Create a pie chart

Step 1: Define the data

To draw the scores of students in the school, for example, define a GradesData class.

class GradesData {
  final String gradeSymbol;
  final int numberOfStudents;

  GradesData(this.gradeSymbol, this.numberOfStudents);
}
Copy the code

Next, prepare some fake data for drawing:


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;
}
Copy the code

Step 2: Define the UI

Next use the PieChart inside charts_flutter to draw the PieChart.

Expanded(
  child: new charts.PieChart(
    _getSeriesData(),
    animate: true,
    defaultRenderer: new charts.ArcRendererConfig(
      arcWidth: 60,
      arcRendererDecorators: [new charts.ArcLabelDecorator()]
    ),
  ),
)
Copy the code

Results:

Complete example:

github

The last

Welcome to follow the wechat public account “Flutter Programming and Development”.