Open In App

Flutter – Create Animated Pie Chart

Last Updated : 15 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Pie charts are an effective way to represent data in a visually appealing and easily understandable format. In Flutter, creating a pie chart is relatively easy with the help of a few external packages. In this article, we will explore how to create a pie chart in Flutter and how to animate it.

Use cases

Following are some of the use cases of a pie chart in a mobile application-

  • Sales and Revenue: Pie charts can be used to show the sales and revenue distribution of a company. The size of each slice represents the proportion of revenue generated by a particular product or service.
  • Expense Tracker: Pie charts can be used to show the breakdown of expenses in a budget or expense tracker app. Each slice represents the proportion of the budget spent on a particular category, such as rent, groceries, or entertainment.
  • User Demographics: Pie charts can be used to show the distribution of users by age, gender, or other demographic factors. Each slice represents the proportion of users in a particular category.
  • Survey Results: Pie charts can be used to show the results of a survey or poll. Each slice represents the percentage of respondents who selected a particular answer option.
  • Task Management: Pie charts can be used to show the progress of tasks in a project management app. Each slice represents the percentage of tasks completed or remaining.

Steps Required

  • Define the data.
  • Create the chart.
  • Define the chart data.
  • Display the chart.

What we are going to build in this article?

Here is a sample video of what we are going to build in this article-

Note: Make sure to have the latest version of Flutter to avoid any kind of errors.

Step By Step Implementation

Step 1: Create a New Project in Android Studio

To set up Flutter Development on Android Studio please refer to Android Studio Setup for Flutter Development, and then create a new project in Android Studio please refer to Creating a Simple Application in Flutter.

Note:

If you like to create a flutter project using terminal use the below command

$ flutter create flutter_app

replace the ‘ flutter_app ‘ with your project name

Step 2: Add dependency

Add the following dependency in pubspec.yaml file-

pie_chart: ^5.1.0

Step 3: Working with the main.dart file

Use the below code in the main.dart file. Comments are added inside the code to understand the code in more detail.

Dart




import 'package:flutter/material.dart';
import 'package:pie_chart/pie_chart.dart';
  
void main() {
  runApp(const MyApp());
}
  
class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);
  
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(),
    );
  }
}
  
class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key}) : super(key: key);
  
  @override
  State<MyHomePage> createState() => _MyHomePageState();
}
  
class _MyHomePageState extends State<MyHomePage> {
  // Data for the pie chart
  Map<String, double> dataMap = {
    "Food Items": 18.47,
    "Clothes": 17.70,
    "Technology": 4.25,
    "Cosmetics": 3.51,
    "Other": 2.83,
  };
  
  // Colors for each segment
  // of the pie chart
  List<Color> colorList = [
    const Color(0xffD95AF3),
    const Color(0xff3EE094),
    const Color(0xff3398F6),
    const Color(0xffFA4A42),
    const Color(0xffFE9539)
  ];
  
  // List of gradients for the 
  // background of the pie chart
  final gradientList = <List<Color>>[
    [
      Color.fromRGBO(223, 250, 92, 1),
      Color.fromRGBO(129, 250, 112, 1),
    ],
    [
      Color.fromRGBO(129, 182, 205, 1),
      Color.fromRGBO(91, 253, 199, 1),
    ],
    [
      Color.fromRGBO(175, 63, 62, 1.0),
      Color.fromRGBO(254, 154, 92, 1),
    ]
  ];
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: const Text("Pie Chart example"),
      ),
      body: Center(
        child: PieChart(
          // Pass in the data for
          // the pie chart
          dataMap: dataMap,
          // Set the colors for the
          // pie chart segments
          colorList: colorList,
          // Set the radius of the pie chart
          chartRadius: MediaQuery.of(context).size.width / 2,
          // Set the center text of the pie chart
          centerText: "Budget",
          // Set the width of the
          // ring around the pie chart
          ringStrokeWidth: 24,
          // Set the animation duration of the pie chart
          animationDuration: const Duration(seconds: 3),
          // Set the options for the chart values (e.g. show percentages, etc.)
          chartValuesOptions: const ChartValuesOptions(
              showChartValues: true,
              showChartValuesOutside: true,
              showChartValuesInPercentage: true,
              showChartValueBackground: false),
          // Set the options for the legend of the pie chart
          legendOptions: const LegendOptions(
              showLegends: true,
              legendShape: BoxShape.rectangle,
              legendTextStyle: TextStyle(fontSize: 15),
              legendPosition: LegendPosition.bottom,
              showLegendsInRow: true),
          // Set the list of gradients for
          // the background of the pie chart
          gradientList: gradientList,
        ),
      ),
    );
  }


Output:

Here is the final output of our application.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads