Flutter - Count List with bool

Viewed 11017

In Flutter I've created a List with booleans.

List<bool> name = [false, false, false]

The Values change to true on a togglebutton click.

How is it possible to count the values on reloading the page?

My attempt was inside the initState to count the List if it contains true.

value = name.contains(true).length

But it always says length isn't defined for the class 'bool'.

How can I count it on reload of the page?

Thanks in advance!

2 Answers

use where instead of contains

value = name.where((item) => item == false).length

bool Iterable.contains(Object element) Returns true if the collection contains an element equal to [element].

This operation will check each element in order for being equal to [element], unless it has a more efficient way to find an element equal to [element].

The equality used to determine whether [element] is equal to an element of the iterable defaults to the [Object.==] of the element.

Some types of iterable may have a different equality used for its elements. For example, a [Set] may have a custom equality (see [Set.identity]) that its contains uses. Likewise the Iterable returned by a [Map.keys] call should use the same equality that the Map uses for keys.

  • from Dart Docs

TLDR: contains returns bool indicating whether the list "contains" an item or not.

Old way but easy to understand... FOR:

int countBoolList(List<bool> boolList) {
  int count = 0;
  for (int i = 0; i < boolList.length; i++) {
    if (boolList.elementAt(i) == true) {
      count++;
    }
  }
  return count;
}

void main() {
  List<bool> name = [false, false, true, false];
  print(countBoolList(name)); //output: 1
}
Related