Home > Net >  generate category statistics based on a list of Map of expenses in flutter
generate category statistics based on a list of Map of expenses in flutter

Time:11-13

I have a list of Map of expenses,

Now I want to generate a statistic list that display all category wised expense and number of entries belongs to that category..

I have solved but I felt my code is very kid way...so looking for advance code for this...

here is my code

List<Map<String, dynamic>> expenses = [
  {
    'category': 'Breakfast',
    'amount': 200,
  },
  {
    'category': 'Breakfast',
    'amount': 190,
  },
  {
    'category': 'Medicine',
    'amount': 400,
  },

];

List<Map<String,dynamic>> generate_category_statistics(List<Map<String,dynamic>> list_expense)
{
  List<Map<String,dynamic>> resultlist=[];

  //want here the code that return a list of map like below output
  //[output:
  // {category: Breakfast, total: 390, number_of_entries: 2},
  // {category: Medicine, total: 400, number_of_entries: 1}],
  return resultlist;
}



void main()
{
  

  print("result =" generate_category_statistics(expenses));

}

CodePudding user response:

You can use collection package like this:

var grouped = groupBy(expenses, (Map value) => value['category']);

var result = grouped.entries
    .map((e) => e.value.length > 1
        ? e.value.reduce((value, element) => {
              "category": element["category"],
              "total":
                  (value['amount'] as int)   (element['amount'] as int),
              "number_of_entries": e.value.length,
            })
        : {
            "category": e.value.first["category"],
            "total": e.value.first["amount"],
            "number_of_entries": 1,
          })
    .toList();

print("result = $result"); //result = [{category: Breakfast, total: 390, number_of_entries: 2}, {category: Medicine, total: 400, number_of_entries: 1}]
  • Related