DEV Community

Cover image for Flutter - Create Simple Bar Chart
Adli Rafif
Adli Rafif

Posted on

Flutter - Create Simple Bar Chart

A. Introduction

Bar Chart is a type of chart which has a function to show the different values of several aspects of data. Because this type of chart is very readable for the user, many developers implement this chart in web and mobile applications.

So in this tutorial, I will show you how to a create simple bar chart using FL Chart Package.

Result Image


B. Step To Create Line Chart

The process of creating a bar chart is quite similar to creating a line chart in the previous tutorial.

For that reason, you can skip steps 1 - 4 If you already follow the previous tutorial.

File Structure

1). Create a Flutter project on your text editor like VS Code or Android Studio. For the detail of creating a new flutter project, you can visit this link : How To Create new Flutter Project

2). Install FL Chart using the below command :

flutter pub add fl_chart
Enter fullscreen mode Exit fullscreen mode

3). In lib folder, create new file named chart_container.dart and insert the below code.

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

class ChartContainer extends StatelessWidget {
  final Color color;
  final String title;
  final Widget chart;

  const ChartContainer({
    Key? key,
    required this.title,
    required this.color,
    required this.chart,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Container(
        width: MediaQuery.of(context).size.width * 0.95,
        height: MediaQuery.of(context).size.width * 0.95 * 0.65,
        padding: EdgeInsets.fromLTRB(0, 10, 20, 10),
        decoration: BoxDecoration(
          color: color,
          borderRadius: BorderRadius.circular(20),
        ),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              title,
              style: TextStyle(
                  color: Colors.white,
                  fontSize: 16,
                  fontWeight: FontWeight.bold),
            ),
            Expanded(
                child: Container(
              padding: EdgeInsets.only(top: 10),
              child: chart,
            ))
          ],
        ),
      ),
    );
  }
}
Enter fullscreen mode Exit fullscreen mode

Explanation :

  • ChartContainer class was created to store a chart and avoid writing the same code repeatedly.
class ChartContainer extends StatelessWidget
Enter fullscreen mode Exit fullscreen mode

4). Make 2 new folder named chart and chart_data inside lib folder.

5). Open main.dart in lib folder, then write the below code.

import 'package:fl_chart_tutorial/chart/bar_chart.dart';
import 'package:fl_chart_tutorial/chart_container.dart';
import 'package:flutter/material.dart';

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

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

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

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(widget.title),
        ),
        body: Container(
          color: Color(0xfff0f0f0),
          child: ListView(
            padding: EdgeInsets.fromLTRB(0, 30, 0, 30),
            children: <Widget>[
              ChartContainer(
                title: 'Bar Chart', 
                color: Color(0xfffc5185), 
                chart: BarChartContent()
              ), 
            ],
          ),
        ));
  }
}

Enter fullscreen mode Exit fullscreen mode

6). Create file inside chart folder named bar_chart.dart. Then create a stateless widget class named BarChartContent.

import 'package:fl_chart/fl_chart.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';

class BarChartContent extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return BarChart(
      BarChartData(),
    );
  }
}
Enter fullscreen mode Exit fullscreen mode

7). Input maximum value of axis Y (ex: maxY: 16) in BarChartData widget. The code will like this.

Widget build(BuildContext context) {
    return BarChart(
      BarChartData(
        maxY: 16,
      ),
    );
  }
Enter fullscreen mode Exit fullscreen mode

Explanation :

  • maxY: 16 is used to give maximum value of y axis.

8). So, we already make basic framework of Bar Chart. After that, we create file called 'bar_chart_data.dart' inside chart_data folder.

bar_chart_data.dart

import 'dart:ui';
import 'package:fl_chart/fl_chart.dart';

List<BarChartGroupData> barChartGroupData = [
  BarChartGroupData(x: 1, barRods: [
    BarChartRodData(y: 10, colors: [Color(0xff43dde6), Color(0xff43dde6)]),
  ]),
   BarChartGroupData(x: 2, barRods: [
    BarChartRodData(y: 8.5, colors: [Color(0xff43dde6), Color(0xff43dde6)]),
  ]),
   BarChartGroupData(x: 3, barRods: [
    BarChartRodData(y: 12.6, colors: [Color(0xff43dde6), Color(0xff43dde6)]),
  ]),
   BarChartGroupData(x: 4, barRods: [
    BarChartRodData(y: 11.4, colors: [Color(0xff43dde6), Color(0xff43dde6)]),
  ]),
   BarChartGroupData(x: 5, barRods: [
    BarChartRodData(y: 7.5, colors: [Color(0xff43dde6), Color(0xff43dde6)]),
  ]),
  BarChartGroupData(x: 6, barRods: [
    BarChartRodData(y: 14, colors: [Color(0xff43dde6), Color(0xff43dde6)]),
  ]),
   BarChartGroupData(x: 7, barRods: [
    BarChartRodData(y: 12.2, colors: [Color(0xff43dde6), Color(0xff43dde6)]),
  ]),
];
Enter fullscreen mode Exit fullscreen mode

Explanation :

  • In this file, we create a list called barChartGroupData which has a purpose to show the bar lines. This list will be added to bar_chart.dart file.
List<BarChartGroupData> barChartGroupData
Enter fullscreen mode Exit fullscreen mode
  • x: 1 is the position of the line bar in the x-axis. For example, we placed the line bar in position 1 on the x-axis.

  • The usage of barRods property in BarChartGroupData is to set height and color of line bars. y: 10 is the height of the a line bar and colors: [Color(0xff43dde6), Color(0xff43dde6)] is the background color of a line bar.

BarChartGroupData(x: 1, barRods: [
    BarChartRodData(y: 10, colors: [Color(0xff43dde6), Color(0xff43dde6)]),
])
Enter fullscreen mode Exit fullscreen mode

9). Well, we have been creating the bar line data of the bar chart. Next we add 'barChartGroupData' list in 'bar_chart.dart' file.

Add this code in top of the line to import bar_chart_data.dart file .

import 'package:fl_chart_tutorial/chart_data/bar_chart_data.dart';
Enter fullscreen mode Exit fullscreen mode

Most important, add barChartGroupData list to BarChartData widget.

barGroups: barChartGroupData
Enter fullscreen mode Exit fullscreen mode

The code will look like this :

bar_chart.dart

import 'package:fl_chart/fl_chart.dart';
import 'package:fl_chart_tutorial/chart_data/bar_chart_data.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';

class BarChartContent extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return BarChart(BarChartData(
      maxY: 16,
      barGroups: barChartGroupData,
    ));
  }
}
Enter fullscreen mode Exit fullscreen mode

Output

Chart 2

10). When we look at the picture above, we see the bottom and left titles are still untouchable. In this step, we customize left and bottom titles using FlTitlesData widget.

The step to customizing titles in a bar chart is similar to a line chart, so you will use the same code from the previous tutorial.

Chart Titles

Open bar_chart.dart file and add this code inside BarChartData widget.

titlesData: FlTitlesData(
          bottomTitles: SideTitles(
            showTitles: true,
            getTextStyles: (value) => TextStyle(
                color: Colors.white, 
                fontSize: 12, 
                fontWeight: FontWeight.bold
              ),
            getTitles: (value) {
              switch (value.toInt()) {
                case 1:
                  return 'Mon';
                case 2:
                  return 'Tues';
                case 3:
                  return 'Wed';
                case 4:
                  return 'Thu';
                case 5:
                  return 'Fri';
                case 6:
                  return 'Sat';
                case 7:
                  return 'Sun';
              }
              return '';
            },
          ),
          leftTitles: SideTitles(
            interval: 4,
            showTitles: true,
            getTextStyles: (value) => TextStyle(
                color: Colors.white, 
                fontSize: 14, 
                fontWeight: FontWeight.bold
              ),
            getTitles: (value) {
              if(value.toInt() == 0) return '';
              else return value.toInt().toString();
            },
          ),
        ),
Enter fullscreen mode Exit fullscreen mode

Explanation :

  • FlTitlesData is a widget which has a function to customize titles around charts. On code above, we only customize left and top tiles.

  • When we look at the last output picture, it seems to have too many titles. To decrease titles amount, we set interval to 4 and when we do that, it change the title for example {0,1,2,3,4,5,6,7,8,9,10} to {0,4,8}.

interval: 4
Enter fullscreen mode Exit fullscreen mode
  • On bottom titles, we change the format from number to day. We must create a custom function to do that and insert that function to getTitles property in SideTitles widget.
getTitles: (value) {
              switch (value.toInt()) {
                case 1:
                  return 'Mon';
                case 2:
                  return 'Tues';
                case 3:
                  return 'Wed';
                case 4:
                  return 'Thu';
                case 5:
                  return 'Fri';
                case 6:
                  return 'Sat';
                case 7:
                  return 'Sun';
              }
              return '';
            },
Enter fullscreen mode Exit fullscreen mode

Output

Chart 3

11). Last, we need to change border style and set bar lines alignment to space-evenly.

borderData: FlBorderData(
          border: Border.all(
            color: Colors.white, 
            width: 0.5
          )
        ),
alignment: BarChartAlignment.spaceEvenly,
Enter fullscreen mode Exit fullscreen mode

The final code of bar_chart.dart will look like this :

import 'package:fl_chart/fl_chart.dart';
import 'package:fl_chart_tutorial/chart_data/bar_chart_data.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';

class BarChartContent extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return BarChart(BarChartData(
      titlesData: FlTitlesData(
        bottomTitles: SideTitles(
          showTitles: true,
          getTextStyles: (value) => TextStyle(
              color: Colors.white, 
              fontSize: 12, 
              fontWeight: FontWeight.bold
            ),
          getTitles: (value) {
            switch (value.toInt()) {
              case 1:
                return 'Mon';
              case 2:
                return 'Tues';
              case 3:
                return 'Wed';
              case 4:
                return 'Thu';
              case 5:
                return 'Fri';
              case 6:
                return 'Sat';
              case 7:
                return 'Sun';
            }
            return '';
          },
        ),
        leftTitles: SideTitles(
          interval: 4,
          showTitles: true,
          getTextStyles: (value) => TextStyle(
              color: Colors.white, 
              fontSize: 14, 
              fontWeight: FontWeight.bold
            ),
          getTitles: (value) {
              if(value.toInt() == 0) return '';
              else return value.toInt().toString();
          },
        ),
      ),
      borderData:
            FlBorderData(
              border: Border.all(
                color: Colors.white, 
                width: 0.5
              )
            ),
      alignment: BarChartAlignment.spaceEvenly,
      maxY: 16,
      barGroups: barChartGroupData,
    ));
  }
}
Enter fullscreen mode Exit fullscreen mode

Final Output
Chart 4

C. Conclusion

I hope this guide will help you to create a bar chart in flutter. Thank You for reading my article.

Next chapter, i will write a tutorial about creating Pie Chart.

For more detail about this tutorial you can check my Github repo at this link: Source Code of Fl Chart Tutorial

Also, if you want to learn more about FL Chart Packages you can visit the documentation link : Fl Chart Documentation

Discussion (0)