'How do I calculate a percentage based on a List of booleans?

I have a list of booleans here:

List<bool> list = [false, false, false, false];

Using that as an example, if I were to find the percentage of values that are true, it would be 0%.

Using another example:

List<bool> list = [true, true, false, false];

The percentage of values that are true would be 50%.

I was able to find something similar to what I need here: Flutter - Count List with bool which works.

However, the calculations to percentages are a little lost on me.



Solution 1:[1]

It's basically just the number of true elements divided by the total number of elements.

void main() {
  List<bool> list = [true, true, false, false];
  double percent = list.where((v) => v).length / list.length;
  String percentString = '${(percent * 100).round()}%';
  print(percent);
  print(percentString);
}

Solution 2:[2]

You should probably do something like :

  int trueValues = list.fold(0, (acc, val) => val ? ++acc : acc);
  double truePercent = trueValues / list.length;

count the number of 'true' value and divide it by the list size (total number of values)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mmcdon20
Solution 2 ThomG