Home > Software design >  Flutter get all map entries where map value matches condition
Flutter get all map entries where map value matches condition

Time:06-26

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

  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;

CodePudding user response:

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);   
  }
  • Related