searchText method

List<T> searchText(
  1. String text, [
  2. String mapper(
    1. T
    )?
])

Performs a text-based search on the list.

Items that start with the search text are returned first, followed by items that contain the text.

A custom mapper can be provided to control how items are converted to searchable strings.

Implementation

List<T> searchText(String text, [String Function(T)? mapper]) {
  final map = this.map(mapper ?? (e) => e.toString()).toList();

  text = text.toLowerCase().trim().noAccent;

  final List<T> start = [];
  final List<T> contains = [];

  for (var i = 0; i < map.length; i++) {
    final v = map[i].toLowerCase().trim().noAccent;

    if (v.startsWith(text)) {
      start.add(this[i]);
    } else if (v.contains(text)) {
      contains.add(this[i]);
    }
  }

  return [...start, ...contains];
}