How to create a bar graph in flutter

This Article is posted by abbas.devcode at 3/28/2020 4:17:59 AM



As a developer, one is sure to encounter tasks related to charts and graphs at some point. In this tutorial, we are going to tackle the task of creating bar graph or bar chart inside a flutter app.
You might also be interested in drawing pie charts for which I've already written a complete tutorial here on fluttercentral.
Moving on, let's see the illustration of what we are going to achieve with this tutorial. It's a nice little bar chart with a simple animation.
The chart will represent the number of mobile apps downloads in billions in the past 3 years.
STEPS TO FOLLOW TO CREATE A BAR GRAPH IN FLUTTER
1. Your first step will be to import the charts_flutter package. You can do it by adding package dependency in your projects pubspec.yaml file. 
dependencies: flutter: sdk: flutter charts_flutter: ^0.9.0
2. Let's create a model class for our data. 
class AppDownloads {
  final String year;

  final double count;

  final charts.Color barColor;

  AppDownloads({
    @required this.year,
    @required this.count,
    @required this.barColor,
  });
}

Please note: You are free to create a separate file for the model class, but for the sake of keeping the tutorial simple I'll be piling up the entire code in a single file.
3. Add the MaterialApp widget and BarGraphDemo in your main.dart file. Here we will import our package as charts.
import 'package:flutter/material.dart';

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

import 'dart:math';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  MyApp({Key key}) : super(key: key);

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

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Bar Graph Demo',
      debugShowCheckedModeBanner: false,
      home: BarGraphDemo(),
      theme: ThemeData(
        primaryColor: Colors.blue,
      ),
    );
  }
}

class BarGraphDemo extends StatefulWidget {
  BarGraphDemo({Key key}) : super(key: key);

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

class _BarGraphDemoState extends State<BarGraphDemo> {
  List<AppDownloads> data;

  @override
  void initState() {
    super.initState();

    data = [
      AppDownloads(
        year: '2017',
        count: 178.1,
        barColor: charts.ColorUtil.fromDartColor(Colors.red),
      ),
      AppDownloads(
        year: '2018',
        count: 205.4,
        barColor: charts.ColorUtil.fromDartColor(Colors.blue),
      ),
      AppDownloads(
        year: '2019',
        count: 258.2,
        barColor: charts.ColorUtil.fromDartColor(Colors.green),
      ),
    ];
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Bar Graph Demo'),
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          Container(
            height: 200,
            width: double.infinity,
            padding: const EdgeInsets.all(12),
            child: Card(
              child: MyBarChart(data),
            ),
          ),
          Padding(
            padding: const EdgeInsets.all(16.0),
            child: Center(
              child: Text(
                'Number of Mobile App Downloads in past 3 years (Data Source: Statista)',
                textAlign: TextAlign.center,
              ),
            ),
          ),
        ],
      ),
    );
  }
}

4.  Finally, create the   MyBarChart class  which we are using inside our BarGraphDemo class.

That's it. You are good to go with this tutorial to draw your own bar charts in flutter.
Leave your questions in comments :)
Keep Fluttering!

Tags: bar graph in flutter








3 Comments
Login to comment.
Recent Comments

ohohabbydale at 11/17/2020

Hi, I followed this kind of code but my labels on the x-axis overlap. How to I rotate the labels? Please help :(

Login to Reply.

sureshmjoshi at 4/28/2020

Hi, I tried this code but I have error on 1. final charts.Color barColor; 2. List<charts.Series<AppDownloads, String>> = [...... import 'package:flutter/material.dart'; import 'package:charts_flutter/flutter.dart' as charts; import 'dart:math'; class ProgressPage extends StatefulWidget{ static const String routeName = "/progress"; ProgressPage(); @override _ProgressPageState createState() => _ProgressPageState(); } class _ProgressPageState extends State<ProgressPage>{ @override Widget build(BuildContext context) { return MaterialApp( title: 'Bar Graph Demo', debugShowCheckedModeBanner: false, home: BarGraphDemo(), theme: ThemeData( primaryColor: Colors.blue, ), ); } } class BarGraphDemo extends StatefulWidget { BarGraphDemo({Key key}) : super(key: key); @override _BarGraphDemoState createState() => _BarGraphDemoState(); } class _BarGraphDemoState extends State { List data; @override void initState() { super.initState(); data = [ AppDownloads( year: '2017', count: 178.1, //barColor: charts.ColorUtil.fromDartColor(Colors.red), ), AppDownloads( year: '2018', count: 205.4, //barColor: charts.ColorUtil.fromDartColor(Colors.blue), ), AppDownloads( year: '2019', count: 258.2, //barColor: charts.ColorUtil.fromDartColor(Colors.green), ), ]; } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Bar Graph Demo'), ), body: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: [ Container( height: 200, width: double.infinity, padding: const EdgeInsets.all(12), child: Card( child: MyBarChart(data), ), ), Padding( padding: const EdgeInsets.all(16.0), child: Center( child: Text( 'Number of Mobile App Downloads in past 3 years (Data Source: Statista)', textAlign: TextAlign.center, ), ), ), ], ), ); } } class MyBarChart extends StatelessWidget { final List data; MyBarChart(this.data); @override Widget build(BuildContext context) { List<charts.Series<AppDownloads, String>> = [ charts.Series( id: 'AppDownloads', data: data, domainFn: (AppDownloads downloads, _) => downloads.year, measureFn: (AppDownloads downloads, _) => downloads.count, //colorFn: (AppDownloads downloads, _) => downloads.barColor ) ]; return charts.BarChart( series, animate: true, barGroupingType: charts.BarGroupingType.groupedStacked, ); } } class AppDownloads { final String year; final double count; final charts.Color barColor; AppDownloads({ this.year, this.count, this.barColor, }); }

Login to Reply.

seven.srikan at 5/6/2020

fixed now. Please check the project over there, https://github.com/srilovesflutter/flutterexamples/tree/master/bargraph












© 2018 - Fluttercentral | Email to me - seven.srikanth@gmail.com