The Wayback Machine - https://web.archive.org/web/20240910065007/https://www.geeksforgeeks.org/flutter-working-with-charts/
Open In App

Flutter – Working with Charts

Last Updated : 15 Feb, 2021
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The syncfusion_flutter_charts library in Flutter is used to handle charts. Charts can be very useful while depicting data in visual form. These packages come with a wide range of beautiful and high-performance charts. It comes with various Cartesian or circular charts with smooth interaction and beautiful animations which are completely customizable and extendable.

In this article, we will look into the same, and with the help of a simple application. To build the app follow the below steps:

  • Add the dependency to the pubspec.yaml file
  • Import the dependency to the main.dart file.
  • Use a StatelessWidget that extends to a StatefulWidget to structure the application
  • Design function that controls the data in the chart
  • Call the required type of built-in chart

Let’s discuss these steps in detail.

Adding the Dependency:

To add the dependency to the pubspec.yaml file, add syncfusion_flutter_charts in the dependencies section as shown below:

dependency

Importing the dependency:

To import the dependency to the main.dart file, use the following code:

import 'package:syncfusion_flutter_charts/charts.dart';

Structuring the Application:

Create a class with a StateFulWidget that further extends to a StatelessWidget to give the app a basic structure with appbar and a body that can hold content as shown below:

Dart




class _ChartApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Charts in Flutter',
      theme: ThemeData(primarySwatch: Colors.blue),
      home: _MyHomePage(),
    );
  }
}
  
class _MyHomePage extends StatefulWidget {
  _MyHomePage({Key key}) : super(key: key);
  
  @override
  _MyHomePageState createState() => _MyHomePageState();
}
  
class _MyHomePageState extends State<_MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text('GeeksForGeeks'),
          backgroundColor: Colors.green,
        ),
        body: 
  }
}


Designing the Function:

Here we will construct a function that  _Infections(), that takes in the COVID-19 data from a fixed set of data points and implement them on the chart based on the month and no. of infections that month. This can be done as follows:

Dart




class _Infections {
  _Infections(this.year, this.victims);
  
  final String year;
  final double victims;
}


This function can be directly used in the body of the application as shown below:

Dart




body: SfCartesianChart(
            primaryXAxis: CategoryAxis(),
            // Chart title
            title: ChartTitle(text: 'Monthly Covid-19 Infections'),
            // Enable legend
            legend: Legend(isVisible: true),
            // Enable tooltip
            tooltipBehavior: TooltipBehavior(enable: true),
            series: <ChartSeries<_Infections, String>>[
              LineSeries<_Infections, String>(
                  dataSource: <_Infections>[
                    _Infections('Jan', 35000),
                    _Infections('Feb', 28000),
                    _Infections('Mar', 34000),
                    _Infections('Apr', 32000),
                    _Infections('May', 40000),
                    _Infections('Jun', 60000)
                  ],
                  xValueMapper: (_Infections victims, _) => victims.year,
                  yValueMapper: (_Infections victims, _) => victims.victims,
                  // Enable data label
                  dataLabelSettings: DataLabelSettings(isVisible: true))
            ]));
  }
}


Complete Source Code:

Dart




import 'package:flutter/material.dart';
import 'package:syncfusion_flutter_charts/charts.dart';
  
void main() {
  return runApp(_ChartApp());
}
  
class _ChartApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Charts in Flutter',
      theme: ThemeData(primarySwatch: Colors.blue),
      home: _MyHomePage(),
    );
  }
}
  
class _MyHomePage extends StatefulWidget {
  // ignore: prefer_const_constructors_in_immutables
  _MyHomePage({Key key}) : super(key: key);
  
  @override
  _MyHomePageState createState() => _MyHomePageState();
}
  
class _MyHomePageState extends State<_MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text('GeeksForGeeks'),
          backgroundColor: Colors.green,
        ),
        body: SfCartesianChart(
            primaryXAxis: CategoryAxis(),
            // Chart title
            title: ChartTitle(text: 'Monthly Covid-19 Infections'),
            // Enable legend
            legend: Legend(isVisible: true),
            // Enable tooltip
            tooltipBehavior: TooltipBehavior(enable: true),
            series: <ChartSeries<_Infections, String>>[
              LineSeries<_Infections, String>(
                  dataSource: <_Infections>[
                    _Infections('Jan', 35000),
                    _Infections('Feb', 28000),
                    _Infections('Mar', 34000),
                    _Infections('Apr', 32000),
                    _Infections('May', 40000),
                    _Infections('Jun', 60000)
                  ],
                  xValueMapper: (_Infections victims, _) => victims.year,
                  yValueMapper: (_Infections victims, _) => victims.victims,
                  // Enable data label
                  dataLabelSettings: DataLabelSettings(isVisible: true))
            ]));
  }
}
  
class _Infections {
  _Infections(this.year, this.victims);
  
  final String year;
  final double victims;
}


Output:



Similar Reads

Flutter - Working with Callback Functions
In this article, we will see how we can use callback functions in flutter. We will learn about different methods to implement callback functions in flutter. Callback is basically a function or a method that we pass as an argument into another function or a method to perform an action. In the simplest words, we can say that Callback or VoidCallback
3 min read
Flutter - Working with Animations
Whenever building an app animation plays a vital role in designing the experience of the user. People tend to like an app that has a smooth flow and a slick design. The Flutter Package provides a variety of methods to create and use animation in our app. We will be discussing the inbuilt Flutter widgets to handle animation. As the flow chart shows
9 min read
Flutter - Working with Layouts
Before talking about Layout in Flutter, there is just one thing to keep in mind that “Everything in Flutter is Widget". Meaning the core of the layout in any Flutter Application is the widget. Putting it simply, all the images, icons, labels and text, etc are technically widgets of different types and layouts. In this article, we will explore the c
6 min read
Flutter - Working with English Words
In Flutter, if you are wondering is there any way to work with English words or where to find any library that works with English words the search ends here. There is a library named english_words that contains at most 5000 used English words with some utility functions. It's useful in applications like dictionaries or teaching-related apps. In thi
3 min read
Flutter - Working with Material Button
Buttons are material components that provide the user a single tap facility for taking actions, making choices, submitting forms, saving data, opening a new page, etc. Buttons are triggered when the user taps on them. They are the most commonly used feature provided in almost all the flutter apps. For using buttons you need to import the Material C
6 min read
Is Flutter Worth Learning? Top 7 Reasons to Learn Flutter
In today's era, the usage of smartphones has increased exponentially and so has the use of mobile applications and websites. Meanwhile, considering future career prospects, learning web development and mobile app development is strongly recommended for all individuals. And when we come to mobile app development, there are two most-popular open-sour
5 min read
Flutter - Sharing Data Among Flutter Pages
In this article, we are going to find the solution for the problem statement "Import/send data from one page to another in flutter". Before going into the topic, there are some pre-requisites. Pre-requisites:Basics of dart programming language.Setting up Flutter in VS code or Setting up Flutter in Android Studio.Creating first flutter app | Hello W
4 min read
Flutter Quill - Rich Text Editor in Flutter Application
This post will explain how to integrate a rich text editor into your Flutter application so that it may enable rich text editing. There are many more things we can do with Flutter Quill, but they can get a little involved. The example below is a pretty basic demonstration of what we mean. Let's first discuss what flutter quill is and why we need it
5 min read
Flutter - Animated AlertDialog in Flutter
Animating an AlertDialog in Flutter involves using the Flutter animations framework to create custom animations for showing and hiding the dialogue. In this article, we are going to add an animation to an AlertDialog. A sample video is given below to get an idea about what we are going to do in this article. [video mp4="https://media.geeksforgeeks.
4 min read
Flutter - Different Types of Loading using Flutter EasyLoading
Flutter applications involve incorporating loading indicators to provide users with feedback during background operations. Flutter has a package for simplifying the process named flutter_easyloading package. This package easiest way to integrate loading indicators with various styles. In this article, we will implement different types of loading in
5 min read
Expandable Widget in Flutter
The expandable widgets do not have a fixed size, they expand on the screen according to the available areas on the screen. Due to size constraints, certain widgets can throw rendering errors, so widgets are made expandable. The one use of expandable widgets is cards that include images, texts, and to further read the text we can click "Read More" o
3 min read
Flutter - Mark as Favorite Feature
Adding to favorites is a prevalent feature in many applications. It enables the users to mark or save images, addressed, links or others stuff for easy future reference. In this article, we are going to see how to implement favorites or add to favorites feature in a flutter application. This article list two methods to do so. In the first method, w
9 min read
Flutter and Blockchain - Hello World Dapp
This tutorial will take you through the process of building your first mobile dapp - Hello World Dapp! This tutorial is meant for those with a basic knowledge of Ethereum and smart contracts, who have some knowledge of the Flutter framework but are new to mobile dapps. In this tutorial we will be covering: Setting up the development environmentCrea
9 min read
Flutter - Animation in Route Transition
Routes are simply Pages in Flutter applications. An application often needs to move from one page to another. But to make these transitions smoother, Animations can be used. These animations can be used to curve or tween the Animation object of the PageRouteBuilder class to alter the transition animation. We will discuss them in detail here. Let's
4 min read
Flutter - Building and Releasing APK using GitHub Actions
Github Actions is a Github tool that allows users to create CI/CD pipelines directly in a Github project instead of going to a third-party website. It assists us in developing, testing, and releasing our project very conveniently. In this article, we're going to build a workflow for our flutter project. We'll first build the project using the workf
3 min read
Flutter - Container Styling
In this article we will look at the most basic and simple widget in flutter Container. We will look that how can we style our container in different ways according to our need , so that we can effectively use this widget in our app . First of all we have to write some starting code for our project . Our code for the structure of our app will go lik
4 min read
Animated Text in Flutter
Animations make the UI more interactive and enhance the user experience. There is no limitation of creativity when it comes to animations or making the application more interactive. In Flutter, we got an easy way to display Animated text. In this article, we will see how we can animate texts using animated_text_kit. Types of Text Animations: Follow
3 min read
Flutter - Set Size to CircularProgressIndicator
In Flutter, we can simply wrap the CircularProgressIndicator widget as a Container widget and gives the height and width of the container that result in the increase and decrease in the size of the CircularProgressIndicator. A sample video is given below to get an idea about what we will do in this article. [video mp4="https://media.geeksforgeeks.o
3 min read
How to Add Route Polylines to Google Maps in Flutter?
Google Maps is used in many Android applications. We can use Polylines to represent routes for various destinations on Google Maps. So in this article, we are going to add Route Polylines to Google Maps in Flutter. Step By Step ImplementationStep 1: Create a New Project in Android StudioTo set up Flutter Development on Android Studio please refer t
4 min read
Flutter - Building an Alarm Clock App
Many applications like the Todo app, Exercise App, require alarm clocks to keep track of time in activities. Or if you want to create an alarm clock app for yourself, you will learn this today. If your app contains features like setting the alarm or setting the timer, how you can do this in Flutter? Don’t worry, it's easy with the flutter_alarm_clo
9 min read
How to Choose the Right Architecture Pattern For Your Flutter App?
One of the key decisions you'll make when building a Flutter app is selecting the right architecture pattern. The architecture pattern determines how your app's code is organized and how its different components interact with each other. Choosing the right architecture can make it easier to build, test, and maintain your app over time. In this arti
4 min read
Flutter - Custom Widgets
We create Custom Widgets when we want a custom look and feel to our app, and we know that there will be a repetition of a particular widget. We can create the custom widget in a new dart file with all the codes and defining the parameters that we need in the constructor. For more on how to split widgets, you can visit the article on Flutter - Split
8 min read
Flutter - ColoredBox Class Widget
A Colored Box is a container that fills it with color according to its child or A widget that paints its area with a specified Color and then draws its child on top of that color. A sample image is given below to get an idea about what we are going to do in this article. How to use it? You can simple use this widget anywhere in your project as you
3 min read
Flutter - Select Single and Multiple Files From Device
We will explore how to select single, or multiple files from our device with different conditions. Sometimes it happens that we want to select only a single type of file or with a fixed extension. If you are looking for the same just read the article till the end. Step By Step Implementation 1. Create your flutter project C/C++ Code 2. Create a sta
6 min read
How to Move Camera to any Position in Google Maps in Flutter?
Google Maps is of the most used application nowadays for navigation. If search for any location our camera on Google Map moves to that position. In this article, we are going to see how to Move the Camera to any Position in Google Maps in Flutter. Step By Step ImplementationStep 1: Create a New Project in Android StudioTo set up Flutter Development
4 min read
How to Get the Height of a Widget in Flutter?
To get the height of a widget in Flutter, you can use the LayoutBuilder widget to obtain the constraints of the parent container and then get the height from those constraints. How to use it? You can simply use this widget anywhere in your project as you needed that. LayoutBuilder( builder: (BuildContext context, BoxConstraints constraints) { doubl
3 min read
Flutter - Handling videos
A video is an important form of media that can be used in the application. In Flutter, videos are handled through the use of video_player plugin. This performs tasks like playing a video, pausing a video, or muting the same. It can be used to play videos from the internet or the videos stored in the assets of the application. In this article, we wi
4 min read
Flutter - Custom Clipper
In flutter, we have widgets and properties that help to create custom shapes. In this article, we will learn about a property called Custom Clipper and we will also implement it to create a curve shape in our UI design. What is a Custom Clipper? Custom Clipper is a property that helps to clip the widget into any shape we want. It clips unused areas
3 min read
How to Add Local Notifications in Flutter?
A push notification is a short message that appears as a pop-up on your desktop browser, mobile home screen, or in your device notification center from a mobile app. For receiving and showcasing push notifications in flutter using local_notifications. There are 3 conditions when we receive notifications When the app is closed.When the app is opened
6 min read
Flutter - SharedPreferences
SharedPreference is a small data storage in our phone where we can store data in pairs of keys and values. We can store an integer, string, list of strings, Boolean, and double in SharedPreferences. Now let us discuss where we can implement these. The first is to save the user information user is logged in or not, any id or some basic user details
6 min read