getOneRandom method

Future<T?> getOneRandom(
  1. String? correlationId,
  2. Function? filter
)

Gets a random item from items that match to a given filter.

This method shall be called by a public getOneRandom method from child class that receives FilterParams and converts them into a filter function.

  • correlationId (optional) transaction id to trace execution through call chain.
  • filter (optional) a filter function to filter items. Return Future that receives a random item Throw error.

Implementation

Future<T?> getOneRandom(String? correlationId, Function? filter) async {
  var items = this.items;

  // Apply filter
  if (filter != null) {
    items = List<T>.from(items.where((item) => filter(item)));
  }

  T? item;
  if (items.isNotEmpty) {
    items.shuffle();
    item = items[0];
  }

  if (item != null) {
    logger.trace(correlationId, 'Retrieved a random item');
  } else {
    logger.trace(correlationId, 'Nothing to return as random item');
  }

  return item;
}