Gabriel
Gabriel

Reputation: 386

Dart: Filter a list based on another list

I have two objects that look like this:

class Field extends RESTModel {
  int id;
  String name;
  String dataType;
  int objectId;
}

class FieldKeywordMap extends RESTModel {
  int id;
  String keywordName;
  int objectConfigurationId;
  int fieldId;
}

I have a list of FieldKeywordMaps called _fieldKeywordMaps and a list of Fields called _selectedFields. I am writing a function to return a filtered version of _fieldKeywordMaps based on 2 conditions:

  1. Where the objectConfigurationId is equal to the selectedObjectConfiguration().id
  2. Where the fieldId is equal to an id of an item in _selectedFields.

Filtering based on the first condition works, but Im having trouble determining how to iterate through my _selectedFields list and compare it to the object in _fieldKeywordMaps. Here is the code:

    selectObjectKeywordMaps() async {
    if (selectedObjectConfiguration() != null && selectedObject() != null) {
      List<FieldKeywordMap> _maps = _fieldKeywordMaps
          .where((keywordMap) =>
              keywordMap.objectConfigurationId == selectedObjectConfiguration().id)
          .where((filteredKeywordMap) =>
              _selectedFields.map((field) => field.id).contains(filteredKeywordMap.id))
          .toList();
      _selectedObjectKeywordMaps = _maps.toList();
      fetchAffectedCustomers();
    } else {
      _selectedObjectKeywordMaps = [];
    }
    notifyListeners();
  }

Upvotes: 2

Views: 4262

Answers (1)

jamesdlin
jamesdlin

Reputation: 89965

.where((filteredKeywordMap) => _selectedFields.map(...)) is inappropriate. Iterable.map is used when you want to perform a 1:1 transformation from one Iterable to another.

You instead could do:

.where((filteredKeywordMap) => _selectedFields.any((field) => field.id == filteredKeywordMap.fieldId))

Note that that can be inefficient. If you made _selectedFields a Map from ids to Fields instead of being a List<Field>s, that would make lookups faster and simpler.

Upvotes: 6

Related Questions