removeItemsByKeys method
Removes multiple items by keys.
Also removes all descendants of the specified items. Throws ArgumentError if none of the keys exist.
Implementation
void removeItemsByKeys(Set<K> keys) {
final existingKeys = keys.where(_itemsMap.containsKey).toSet();
if (existingKeys.isEmpty) {
throw ArgumentError.value(keys, 'keys', 'No matching items found');
}
// Collect all descendants for the keys being removed.
final allToRemove = <K>{...existingKeys};
for (final key in existingKeys) {
allToRemove.addAll(getDescendantsOfKey(key));
}
// Update parent childrenKeys if parent is NOT also being removed.
for (final key in existingKeys) {
final item = _itemsMap[key];
if (item != null && item.parentKey != null && !allToRemove.contains(item.parentKey)) {
final parentItem = _itemsMap[item.parentKey!];
if (parentItem != null && parentItem.childrenKeys != null) {
final updatedChildrenKeys = parentItem.childrenKeys!.where((k) => !allToRemove.contains(k)).toList();
_itemsMap[parentItem.key] = itemFactory(
parentItem.data,
parentKey: parentItem.parentKey,
childrenKeys: updatedChildrenKeys.isNotEmpty ? updatedChildrenKeys : null,
level: parentItem.level,
);
// Sync updated parent back into _localPaginationItems and displayItems.
_syncParentInLocalAndDisplay(parentItem.key);
}
}
}
_itemsMap.removeWhere((k, _) => allToRemove.contains(k));
if (_useLocalPaginationItems) {
_localPaginationItems.removeWhere((x) => allToRemove.contains(x.key));
}
final displayItems = value.displayItems;
final newDisplayItems = displayItems.where((x) => !allToRemove.contains(x.key)).toList();
final newSelectedKeys = copyKeySet(value.selectedKeys)..removeAll(allToRemove);
final newExpandedKeys = copyKeySet(value.expandedKeys)..removeAll(allToRemove);
final clearExpandedDetail = value.expandedDetailKey != null && allToRemove.contains(value.expandedDetailKey);
final clearEditingItem = value.editingItemKey != null && allToRemove.contains(value.editingItemKey);
updateState(
who: 'removeItems',
displayItems: newDisplayItems,
// Fix: subtract ALL removed items (including descendants), not just the top-level keys.
totalItems: value.totalItems - allToRemove.length,
selectedKeys: newSelectedKeys,
expandedKeys: newExpandedKeys,
clearExpandedDetail: clearExpandedDetail,
clearEditingItem: clearEditingItem,
);
}