search method
Performs a full-text search, optional multi-criteria sort, and pagination on the box values.
query: The search string. Split into terms (by whitespace), all of which must be present (case-insensitive) in the value as determined bysearchableText. If empty, all values are returned.searchableText: A function mapping a value to a string to be searched.page: Optional page number (zero-based) for pagination. If null, all results are returned.pageSize: Number of items per page (default: 20).sortBy: Optional list of SortCriterions to sort the results by multiple fields.
Returns a Future that completes with a list of matching values, sorted and paginated as requested.
Throws BoxNotInitializedException if the box is not initialized.
Implementation
Future<List<T>> search({
required String query,
required String Function(T item) searchableText,
int? page,
int pageSize = 20,
List<SortCriterion<T>>? sortBy,
}) async {
await ensureInitialized();
// Split the query into lowercase search terms, ignoring empty terms.
final searchTerms = query
.toLowerCase()
.split(RegExp(r'\s+'))
.map((e) => e.trim())
.where((e) => e.isNotEmpty)
.toList();
// If no search terms, return all values; otherwise, filter by all terms.
final filtered = searchTerms.isEmpty
? await getAllValues()
: await getValuesWhere((item) {
final text = searchableText(item).toLowerCase();
return searchTerms.every((term) => text.contains(term));
});
final resultList = filtered.toList();
// Apply multi-criteria sorting if specified.
if (sortBy != null && sortBy.isNotEmpty) {
resultList.sort((a, b) {
for (final criterion in sortBy) {
final result = criterion.compare(a, b);
if (result != 0) return result;
}
return 0;
});
}
// If no pagination requested, return the full result list.
if (page == null) return resultList;
// Return the paginated results.
return _paginate(resultList, page, pageSize);
}