Uncategorized

How to Display PieChart in Flutter

At first create a database which contains order data and specially the status.

-- Create the database
CREATE DATABASE orders_db;

-- Use the newly created database
USE orders_db;

-- Create the orders table
CREATE TABLE orders (
    id INT PRIMARY KEY,
    chk_bill_name VARCHAR(255),
    chk_bill_phone VARCHAR(20),
    chk_bill_email VARCHAR(255),
    chk_bill_country VARCHAR(100),
    chk_bill_state VARCHAR(100),
    chk_bill_city VARCHAR(100),
    chk_bill_zip VARCHAR(10),
    chk_bill_street_addr VARCHAR(255),
    chk_product_ids VARCHAR(255),
    chk_product_name VARCHAR(255),
    chk_net DECIMAL(10, 2),
    chk_date DATETIME,
    chk_status VARCHAR(50),
    chk_payment_mode VARCHAR(50),
    chk_type VARCHAR(50),
    chk_payment_status VARCHAR(50),
    chk_request TEXT
);

Create The Empty Flutter Screen Called OrderPieChart

import 'package:flutter/cupertino.dart';

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

  @override
  State<OrderPieChart> createState() => _OrderPieChartState();
}

class _OrderPieChartState extends State<OrderPieChart> {
  @override
  Widget build(BuildContext context) {
    return const Placeholder();
  }
}

Install Necessary Packages in pubscpec.yaml

pie_chart: ^5.4.0 

Import Dependencies in OrderPieChart Screen

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

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

  @override
  State<OrderPieChart> createState() => _OrderPieChartState();
}

class _OrderPieChartState extends State<OrderPieChart> {
  @override
  Widget build(BuildContext context) {
    return const Placeholder();
  }
}

Import Other Dependencies

import 'package:flutter/cupertino.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'dart:async';

Create The Variables

 String id = "";
  String userName = "";
  String status = "";
  String phone = "";
  String userMobile = '';
  String userStudent = '';

  List<dynamic> _userData = [];
 bool _isLoading = true;
  bool _hasError = false;

//Required For Pie Chart
Map<String, double> dataMap = {
    "Success": 0,
    "Pending": 0,
    "Cancelled": 0,
  };

Create Function to get User Details From The Shared Preferences

Future<void> _getUserInfo() async {
    try {
      SharedPreferences prefs = await SharedPreferences.getInstance();
      String usermobile = prefs.getString('userMobile') ?? ''; // Get user mobile
      String userNameValue = prefs.getString('userName') ?? ''; // Get user name

      if (usermobile.isEmpty) {
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => Login(),
          ),
        );
      } else {
        setState(() {
          userMobile = usermobile;
          userName = userNameValue; // Update userName
        });

        
      }
    } catch (error) {
      print('Error retrieving user info: $error');
    }
  }

Initiate _getUserInfo for default loading

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

Create _checkout function to check order details

Future<void> _checkOut() async {
final String apiUrl = 'https://indiawebdesigns.in/corporate-admin/controllers/Flutter/check_recordings.php?id=$userMobile';
try {
final response = await http.get(Uri.parse(apiUrl));

if (response.statusCode == 200) {
final List<dynamic> data = json.decode(response.body);
setState(() {
_userData = data;
_isLoading = false;
});
_updateDataMap(data);
} else {
throw Exception('Failed to load data');
}
} catch (error) {
setState(() {
_hasError = true;
_isLoading = false;
});
}
}

Now call _checkOut function once the _getUserInfo function is loaded up

Future<void> _getUserInfo() async {
try {
SharedPreferences prefs = await SharedPreferences.getInstance();
String usermobile = prefs.getString('userMobile') ?? ''; // Get user mobile
String userNameValue = prefs.getString('userName') ?? ''; // Get user name

if (usermobile.isEmpty) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Login(),
),
);
} else {
setState(() {
userMobile = usermobile;
userName = userNameValue; // Update userName
});

_checkOut();
}
} catch (error) {
print('Error retrieving user info: $error');
}
}

PHP Api code of fetching data using PHP


<?php
ob_start();
include('../../database.php');
header("Access-Control-Allow-Origin: *");
DB::connect();

$id = $_GET['id'];

$select_master_user = "SELECT * FROM  `checkout` where  chk_bill_phone = '$id'  and chk_type = 'Learn' order by id desc";
$sql999 = $dbconn->prepare($select_master_user);
$sql999->execute();
$wlvd999 = $sql999->fetchAll(PDO::FETCH_ASSOC);

// Convert all values to strings
foreach ($wlvd999 as &$item) {
    foreach ($item as &$value) {
        $value = (string)$value;
    }
}

$json = json_encode($wlvd999, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);

header('Content-Type: application/json; charset=utf-8');
echo str_replace('\\/', '/', $json);

Update The Dynamic List

 void _updateDataMap(List<dynamic> data) {
    Map<String, double> updatedDataMap = {
      "Success": 0,
      "Pending": 0,
      "Cancelled": 0,
    };

    for (var item in data) {
      String paymentStatus = item['chk_payment_status'];
      if (updatedDataMap.containsKey(paymentStatus)) {
        updatedDataMap[paymentStatus] = (updatedDataMap[paymentStatus] ?? 0) + 1;
      } else {
        updatedDataMap[paymentStatus] = 1;
      }
    }

    setState(() {
      dataMap = updatedDataMap;
    });
  }

Design the UI

@override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Row(
          children: [
            Text('Hi ', style: TextStyle(color: Colors.white)),
            Text(userName, style: TextStyle(color: Colors.white)),
          ],
        ),
        backgroundColor: Colors.black,
        iconTheme: IconThemeData(color: Colors.white),
      ),
      body: SingleChildScrollView(
        child: Column(
          children: [
            SizedBox(height: 30,),
            PieChart(
              dataMap: dataMap,
              animationDuration: Duration(milliseconds: 800),
              chartLegendSpacing: 32,
              chartRadius: MediaQuery.of(context).size.width / 2.7,
              colorList: [Colors.green, Colors.orange, Colors.red],
              initialAngleInDegree: 0,
              chartType: ChartType.ring,
              ringStrokeWidth: 32,
              centerText: "Orders",
              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: false,
                decimalPlaces: 1,
              ),
            ),

          ],
        ),
      ),
    );
  }

Complete Flutter Code

import 'package:flutter/material.dart';
import 'package:pie_chart/pie_chart.dart';
import 'package:prodwebotapp/Login/login.dart';
import 'package:flutter/cupertino.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'dart:async';
import 'MyCourseNew.dart';

class OrderPieChart extends StatefulWidget {
  @override
  State<OrderPieChart> createState() => _OrderPieChartState();
}

class _OrderPieChartState extends State<OrderPieChart> {
  String id = "";
  String userName = "";
  String status = "";
  String phone = "";
  String userMobile = '';
  String userStudent = '';

  List<dynamic> _userData = [];
  bool _isLoading = true;
  bool _hasError = false;

  Map<String, double> dataMap = {
    "Success": 0,
    "Pending": 0,
    "Cancelled": 0,
  };

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

  Future<void> _getUserInfo() async {
    try {
      SharedPreferences prefs = await SharedPreferences.getInstance();
      String usermobile = prefs.getString('userMobile') ?? ''; // Get user mobile
      String userNameValue = prefs.getString('userName') ?? ''; // Get user name

      if (usermobile.isEmpty) {
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => Login(),
          ),
        );
      } else {
        setState(() {
          userMobile = usermobile;
          userName = userNameValue; // Update userName
        });

        _checkOut();
      }
    } catch (error) {
      print('Error retrieving user info: $error');
    }
  }

  Future<void> _checkOut() async {
    final String apiUrl = 'https://indiawebdesigns.in/corporate-admin/controllers/Flutter/check_recordings.php?id=$userMobile';
    try {
      final response = await http.get(Uri.parse(apiUrl));

      if (response.statusCode == 200) {
        final List<dynamic> data = json.decode(response.body);
        setState(() {
          _userData = data;
          _isLoading = false;
        });
        _updateDataMap(data);
      } else {
        throw Exception('Failed to load data');
      }
    } catch (error) {
      setState(() {
        _hasError = true;
        _isLoading = false;
      });
    }
  }

  void _updateDataMap(List<dynamic> data) {
    Map<String, double> updatedDataMap = {
      "Success": 0,
      "Pending": 0,
      "Cancelled": 0,
    };

    for (var item in data) {
      String paymentStatus = item['chk_payment_status'];
      if (updatedDataMap.containsKey(paymentStatus)) {
        updatedDataMap[paymentStatus] = (updatedDataMap[paymentStatus] ?? 0) + 1;
      } else {
        updatedDataMap[paymentStatus] = 1;
      }
    }

    setState(() {
      dataMap = updatedDataMap;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Row(
          children: [
            Text('Hi ', style: TextStyle(color: Colors.white)),
            Text(userName, style: TextStyle(color: Colors.white)),
          ],
        ),
        backgroundColor: Colors.black,
        iconTheme: IconThemeData(color: Colors.white),
      ),
      body: SingleChildScrollView(
        child: Column(
          children: [
            SizedBox(height: 30,),
            PieChart(
              dataMap: dataMap,
              animationDuration: Duration(milliseconds: 800),
              chartLegendSpacing: 32,
              chartRadius: MediaQuery.of(context).size.width / 2.7,
              colorList: [Colors.green, Colors.orange, Colors.red],
              initialAngleInDegree: 0,
              chartType: ChartType.ring,
              ringStrokeWidth: 32,
              centerText: "Orders",
              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: false,
                decimalPlaces: 1,
              ),
            ),

          ],
        ),
      ),
    );
  }
}

One thought on “How to Display PieChart in Flutter

Leave a Reply

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