Home > Net >  Flutter - Calculate Sum and Percentage of total items in a list
Flutter - Calculate Sum and Percentage of total items in a list

Time:06-14

I am having trouble calculating the sum and percentage of items in the list:

list = [
GenderAgeView(gender: M, total: 3), 
GenderAgeView(gender: F, total: 35),
GenderAgeView(gender: U, total: 1), 
GenderAgeView(gender: M, total: 45), 
GenderAgeView(gender: M, total: 65), 
GenderAgeView(gender: M, total: 1), 
GenderAgeView(gender: F, total: 8), 
GenderAgeView(gender: U, total: 1), 
GenderAgeView(gender: F, total: 43), 
GenderAgeView(gender: M, total: 50), 
GenderAgeView(gender: F, total: 31), 
GenderAgeView(gender: F, total: 16), 
GenderAgeView(gender: M, total: 36), 
GenderAgeView(gender: F, total: 50), 
GenderAgeView(gender: M, total: 23)
]

EDIT - I want to retrieve the dataPoints() method. I want to group and calculate the sum and percentage... The output should look like this:

GenderAgeView(gender: M, total: 120), 
GenderAgeView(gender: F, total: 100),
GenderAgeView(gender: U, total: 2)

What I have done so far:

List<GenderAgeView> dataPoints() {
    // var data is my main list I get the data from the API call
    var data = genderAgeControllerData.genderAgeList;
    // Here I create a list and check if for null empty values on attribute gender
    var list = data.where((m) => m.gender != '').map<GenderAgeView>((m) {
      return GenderAgeView(
        gender: m.gender,
        total: m.total,
      );
    }).toList();

    return list;
  }

I am not sure if I have to use reduce to sum and then divide by the length of the list...

Please, can you assist? Thanks

CodePudding user response:

Use the https://pub.dev/packages/collection package from pub.dev. I imported it using:

import 'package:collection/collection.dart';

Then use this bit of code. The groupBy creates a map with the keys being the gender and the entry being a list of GenderAgeViews. Then, you iterate over every key in the map and add a GenderAgeView object to the resultList. The fold method then takes all entries and counts the total of every one of them, which is then used in the constructor.

List<GenderAgeView> dataPoints() {
  List<GenderAgeView> data = genderAgeControllerData.genderAgeList;
  final groupedMap = col.groupBy(data, (GenderAgeView data) => data.gender);
  List resultList = [];
  groupedMap.forEach((key, entries) {
    resultList.add(GenderAgeView(gender: key, total: entries.fold(0, (total,cur) => total   cur.total)));
  });
  return resultList;
}
  • Related