Home > Enterprise >  Flutter) How to count to specific values inside map
Flutter) How to count to specific values inside map

Time:01-02

I have a map looks like this

 Map<String, String> vaccinated = {
    'dog': 'ready',
    'cat': 'ready',
    'mouse': 'done',
    'horse': 'done',
  };

and I would like to count only 'done' inside the map and wants a result of

2 

but the thing I've tried showed me is only boolean anyone knows how can I count specific values inside map

CodePudding user response:

You can do it like

void main() {
  Map<String, String> vaccinated = {
    'dog': 'ready',
    'cat': 'ready',
    'mouse': 'done',
    'horse': 'done',
  };

  final total =
      vaccinated.entries.where((e) => e.value == "done").toList().length;

  print(total);
}

More about Map

CodePudding user response:

You can fold the values of the map to get the count.

Map<String, String> vaccinated = {
  'dog': 'ready',
  'cat': 'ready',
  'mouse': 'done',
  'horse': 'done',
};

int count = vaccinated.values.fold(0, (value, current) => value   (current == 'done' ? 1 : 0));
print(count);

Check out the fold method: https://api.flutter.dev/flutter/dart-core/Iterable/fold.html

  • Related