How to Implement a Pie Chart in Flutter?

Spread the love
piechartflutter
piechartflutter

Introduction:

Pie charts are effective visualizations for displaying data distribution. In Flutter, you can implement a pie chart using the pie_chart package. This step-by-step guide will walk you through the process of creating a pie chart in Flutter.

Content:

Step 1: Create a New Flutter Project

Ensure that you have Flutter installed and set up on your machine. Create a new Flutter project using the following command in your terminal:


flutter create pie_chart_example

Step 2: Add the pie_chart Dependency

Open the pubspec.yaml file in your Flutter project and add the ‘pie_chart’ dependency:


dependencies:
  pie_chart: ^5.4.0

Save the file and run flutter pub get in your terminal.

Step 3: Implement a Pie Chart in Flutter

Open the lib/main.dart file and replace its content with the following code:


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

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

class PieChartApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    Map<String, double> dataMap = {
      'Flutter': 5,
      'React': 3,
      'Angular': 2,
      'Vue': 1,
    };

    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Pie Chart Example'),
        ),
        body: Center(
          child: PieChart(
            dataMap: dataMap,
            chartRadius: 300,
            chartType: ChartType.disc,
            chartLegendSpacing: 48,
            showChartValuesInPercentage: true,
            showChartValuesOutside: true,
            chartValuesColor: Colors.blueGrey[900].withOpacity(0.9),
            legendPosition: LegendPosition.right,
            legendStyle: TextStyle(
              color: Colors.black,
              fontWeight: FontWeight.bold,
            ),
          ),
        ),
      ),
    );
  }
}

Step 4: Run the App

Save your changes and run the app using the following command in your terminal:

Sample Code:


// ignore_for_file: prefer_const_constructors

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

class PieChartSample2 extends StatefulWidget {
  const PieChartSample2({super.key});

  @override
  State<StatefulWidget> createState() => PieChart2State();
}

class PieChart2State extends State {
  int touchedIndex = -1;
  Map<String, double> dataMap = {
    "Flutter": 5,
    "React": 3,
    "Xamarin": 2,
    "Ionic": 2,
  };
  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,
        elevation: 2,
        title: Text("Qr Generator page"),
        backgroundColor: Colors.blue[200],
      ),
      body: Column(
        children: [
          SizedBox(
            height: 10,
          ),
          Text(
            "1.Pie Chart with value inside of circle ",
            style: TextStyle(color: Colors.black, fontSize: 18, fontWeight: FontWeight.bold),
          ),
          SizedBox(
            height: 30,
          ),
          PieChart(
            dataMap: dataMap,
            animationDuration: Duration(milliseconds: 800),
            chartLegendSpacing: 32,
            chartRadius: MediaQuery.of(context).size.width / 3.2,
            // colorList: colorList,
            initialAngleInDegree: 0,
            chartType: ChartType.ring,
            ringStrokeWidth: 42,
            centerText: "HYBRID",
            legendOptions: LegendOptions(
              showLegendsInRow: false,
              legendPosition: LegendPosition.right,
              showLegends: true,
              // legendShape: _BoxShape.circle,
              legendTextStyle: TextStyle(
                fontWeight: FontWeight.bold,
              ),
            ),
            chartValuesOptions: ChartValuesOptions(
              showChartValueBackground: true,
              showChartValues: true,
              showChartValuesInPercentage: false,
              showChartValuesOutside: false,
              decimalPlaces: 1,
            ),
            // gradientList: ---To add gradient colors---
            // emptyColorGradient: ---Empty Color gradient---
          ),
          SizedBox(
            height: 50,
          ),
          Text(
            "2.Pie Chart with value Outside of circle ",
            style: TextStyle(color: Colors.black, fontSize: 18, fontWeight: FontWeight.bold),
          ),
          SizedBox(
            height: 30,
          ),
          PieChart(
            dataMap: dataMap,
            animationDuration: Duration(milliseconds: 800),
            chartLegendSpacing: 32,
            chartRadius: MediaQuery.of(context).size.width / 3.2,
            // colorList: colorList,
            initialAngleInDegree: 0,
            chartType: ChartType.ring,

            ringStrokeWidth: 22,
            centerText: "HYBRID",
            legendOptions: LegendOptions(
              showLegendsInRow: false,
              legendPosition: LegendPosition.right,
              showLegends: true,
              // legendShape: _BoxShape.circle,
              legendTextStyle: TextStyle(
                fontWeight: FontWeight.bold,
              ),
            ),
            chartValuesOptions: ChartValuesOptions(
              showChartValueBackground: true,
              showChartValues: true,
              showChartValuesInPercentage: false,
              showChartValuesOutside: true,
              decimalPlaces: 1,
            ),
            // gradientList: ---To add gradient colors---
            // emptyColorGradient: ---Empty Color gradient---
          ),
          SizedBox(
            height: 50,
          ),
          Text(
            "3.Pie Chart with Gradient Color in circle",
            style: TextStyle(color: Colors.black, fontSize: 18, fontWeight: FontWeight.bold),
          ),
          SizedBox(
            height: 30,
          ),
          PieChart(
            dataMap: dataMap,
            animationDuration: Duration(milliseconds: 800),
            chartLegendSpacing: 32,
            chartRadius: MediaQuery.of(context).size.width / 3.2,
            // colorList: colorList,
            initialAngleInDegree: 0,
            chartType: ChartType.ring,

            gradientList: gradientList,
            ringStrokeWidth: 22,
            // ignore: prefer_const_literals_to_create_immutables
            emptyColorGradient: [
              Color(0xff6c5ce7),
              Colors.blue,
            ],
            centerText: "HYBRID",
            legendOptions: LegendOptions(
              showLegendsInRow: false,
              legendPosition: LegendPosition.right,
              showLegends: true,
              legendShape: BoxShape.circle,
              legendTextStyle: TextStyle(
                fontWeight: FontWeight.bold,
              ),
            ),
            chartValuesOptions: ChartValuesOptions(
              showChartValueBackground: true,
              showChartValues: true,
              showChartValuesInPercentage: true,
              showChartValuesOutside: true,
              decimalPlaces: 1,
            ),
            // gradientList: ---To add gradient colors---
            // emptyColorGradient: ---Empty Color gradient---
          ),
        ],
      ),
    );
  }
}

Output:

piechartflutter
piechartflutter

Conclusion:

In this guide, we’ve demonstrated how to implement a pie chart in Flutter using the pie_chart package. The example app displays a simple pie chart with data distribution among different technologies. You can customize the chart appearance, colors, and other properties according to your application’s needs. Explore additional features provided by the pie_chart package to enhance your pie chart implementation in Flutter.

 

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *