Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Flutter get all map entries where map value matches condition

I am trying to find all elements in a Map where a condition is met.

My widget receives final Map<String, Item> itemMap; from a Parent Widget

I have a function that gets called when a Dropdown element is selected

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  handleTypeSelect(String? selectedType) {
    var newList = widget.itemMap.entries
        .where((element) => element.value.type == selectedType)
        .toList();

    var foo = Map<String, Item>.fromIterable(newList);
    var bar = Map<String, Item>.fromEntries(newList);
    print('newlist ${bar}');
   
  }

All I need is to create a new Map with the same structure Map<String, Item> that only contains the map entries where Item.type matched the type selected from the dropdown. I tried several things but always ended up with different errors like: Expected a value of type 'String', but got one of type 'MapEntry<String, Item>' or some Map of entries that I am unable to access.

Item Model is probably not relevant but just in case it helps.

  final String name;
  final String id;
  final String type;
  final int circulation;
  final String description;
  final String imageLink;
  final int marketValue;

>Solution :

Try the following:

Map<int, bool> example = {1: true, 2: false};
var trueEntries = example.entries.where((MapEntry e) => e.value);
print(Map.fromEntries(trueEntries));

Which yields {1: true}.

In your code it would probably be something like this:

  handleTypeSelect(String? selectedType) {
    var filteredEntries = widget.itemMap.entries
        .where((MapEntry e) => e.value.type == selectedType);
    var bar = Map.fromEntries(newList);   
  }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading