'Getting a total count of key occurrences

I have a nested List that I've converted from a map:

final currentWeek = userProgram.weekMap[userProgram.currentWeek]?.values.toList();

Which gives me a dataset of more Lists, like this:

enter image description here

enter image description here

Each of these Lists has a completed key. I want to get a total count of this specific key so that I can do calculations based off of it.

I've tried doing nested for loops to get to this value, but I'm a little lost on getting the count of all the completed keys.

currentWeek?.forEach((e) {
  e.forEach((d) {
    print(d.completed);
  });
});


Solution 1:[1]

Just use a simple loop and increment a variable:

var completedCount = 0;
for (var e in currentWeek ?? []) {
  for (var d in e) {
    if (d.completed) {
      completedCount += 1;
    }
  }
}
print(completedCount);

Alternatively, if you prefer a functional approach:

var completedCount = currentWeek?.fold<int>(
      0,
      (countSoFar, step) => countSoFar + (step.completed ? 1 : 0),
    ) ??
    0;

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 jamesdlin