DEV Community

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

Posted on • Updated on

Flutter  -  Create Simple Line Chart

A. Introduction

The chart feature on mobile development is very useful for a user to more understand some data set. The application display will look professional if the chart showing animation and a great display.

This time, we will create a Line Chart using FL Chart Package.

Result Image


B. Step To Create Line Chart

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). Open main.dart in lib folder, then write the below code.

import 'package:fl_chart_tutorial/chart/line_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: 'Line Chart', 
                color: Color.fromRGBO(45, 108, 223, 1), 
                chart: LineChartContent(),
              ), 
            ],
          ),
        ));
  }
}

Enter fullscreen mode Exit fullscreen mode

4). 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

5). Create a new folder named chart in lib folder, then create file inside chart folder named line_chart.dart .

Insert import code at the top of the line.

import 'package:fl_chart/fl_chart.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
Enter fullscreen mode Exit fullscreen mode

6). Next, create a stateless widget class named LineChartContent.

class LineChartContent extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return LineChart(
      LineChartData(),
    );
  }
}
Enter fullscreen mode Exit fullscreen mode

7). Input minimum and maximum value of axis X (ex: minX: 1 & maxX: 7) and axis Y (ex: minY: 0 & maxY: 16) In LineChartData widget, . The code will like this.

Widget build(BuildContext context) {
    return LineChart(
      LineChartData(
        minX: 1,
        minY: 0,
        maxX: 7,
        maxY: 16,
      ),
    );
  }
Enter fullscreen mode Exit fullscreen mode

8). To create a chart line based on data, create folder chart_data then make dart file line_chart_data.dart .

line_chart_data.dart

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

List<Color> lineColor = [
    Color(0xfff3f169),
];

List<LineChartBarData> lineChartBarData = [
  LineChartBarData(
    colors: lineColor,
    isCurved: true,
    spots: [
      FlSpot(1, 8),
      FlSpot(2, 12.4),
      FlSpot(3, 10.8),
      FlSpot(4, 9),
      FlSpot(5, 8),
      FlSpot(6, 8.6),
      FlSpot(7, 10)
    ]
  )
];
Enter fullscreen mode Exit fullscreen mode

Explanation :

  • lineChartBarData is a list that used to show the chart's line .
List<LineChartBarData> lineChartBarData
Enter fullscreen mode Exit fullscreen mode
  • FlSpot(x, y) is a syntax to draw x (x starts from left) and y (y starts from bottom) coordinate.
FlSpot(x, y)
Enter fullscreen mode Exit fullscreen mode

9). After we create lineChartBarData list, we must add this list on file line_chart.dart .

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

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

Most important, add lineChartBarData list to LineChartData widget.

lineBarsData: lineChartBarData
Enter fullscreen mode Exit fullscreen mode

line_chart.dart

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

class LineChartContent extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return LineChart(
      LineChartData(
        minX: 1,
        minY: 0,
        maxX: 7,
        maxY: 16,
        lineBarsData: lineChartBarData,
      ),
    );
  }
}
Enter fullscreen mode Exit fullscreen mode

Output

Chart 2

10). In the picture above, you see on left titles and bottom titles still untouchable. We must customize it to make it readable by the user.

Chart Titles

Go to line_chart.dart file and add this code inside LineChartData 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 step, we need to change the border color to white and remove the horizontal line.

borderData: FlBorderData(
          border: Border.all(
            color: Colors.white, 
            width: 0.5
          )
        ),
gridData: FlGridData(
          drawHorizontalLine: false,
        ),
Enter fullscreen mode Exit fullscreen mode

The final code of line chart will look like this :

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

class LineChartContent extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return LineChart(
      LineChartData(
        borderData: FlBorderData(
          border: Border.all(
            color: Colors.white, 
            width: 0.5
          )
        ),
        gridData: FlGridData(
          drawHorizontalLine: false,
        ),
        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();
            },
          ),
        ),
        minX: 1,
        minY: 0,
        maxX: 7,
        maxY: 16,
        lineBarsData: lineChartBarData,
      ),
    );
  }
}

Enter fullscreen mode Exit fullscreen mode

Final Output
Chart 4

C. Conclusion

So, this is a tutorial about creating a line chart using Fl Chart. I hope this tutorial will be helpful for you.

In the next chapter, we will learn about creating a bar 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)