removeWhere<T extends StorableModel> method

Future<void> removeWhere<T extends StorableModel>(
  1. String tag,
  2. T fromJson(
    1. Map<String, dynamic>
    ),
  3. bool condition(
    1. T item
    )
)

Deletes items from the data store associated with a specific tag if they match a given condition.

This method retrieves the data corresponding to the provided tag, converts each entry to an object of type T using the fromJson function, applies the condition to each object, and removes entries that satisfy the condition. The updated data is then saved back to the storage.

Type Parameters:

  • T: A type extending StorableModel that represents the model of the data.

Parameters:

  • tag: A String representing the category or group of data to target.
  • fromJson: A function that converts a Map<String, dynamic> to an object of type T.
  • condition: A predicate function that takes an item of type T and returns a bool. Items for which this function returns true will be deleted.

Returns:

  • A Future<void> indicating the completion of the delete operation.

Throws:

  • Any errors encountered during data loading or saving will propagate.

Implementation

Future<void> removeWhere<T extends StorableModel>(
  final String tag,
  final T Function(Map<String, dynamic>) fromJson,
  final bool Function(T item) condition,
) async {
  final Map<String, dynamic> data = await _loadData(tag);
  final List<String> idsToRemove = <String>[];

  data.forEach((final String id, final dynamic value) {
    final T item = fromJson(value as Map<String, dynamic>);
    if (condition(item)) {
      idsToRemove.add(id);
    }
  });

  for (int i = 0; i < idsToRemove.length; i++) {
    final String id = idsToRemove[i];
    data.remove(id);
  }

  await _saveData(tag, data);
}