addToHistory method
- String query
Saves a search query to history.
If the query already exists, increments its usage count and updates the timestamp. If the history exceeds maxHistoryItems, removes the oldest entries.
Implementation
Future<void> addToHistory(String query) async {
_ensureInitialized();
final normalizedQuery = query.trim().toLowerCase();
if (normalizedQuery.isEmpty) return;
// Check if query already exists
final existingKey = _box!.keys.firstWhere(
(key) => _box!.get(key)?.query.toLowerCase() == normalizedQuery,
orElse: () => null,
);
if (existingKey != null) {
// Update existing item
final item = _box!.get(existingKey)!;
item.recordUsage();
await item.save();
} else {
// Add new item
final item = SearchHistoryItem(
query: query.trim(),
timestamp: DateTime.now(),
);
await _box!.add(item);
// Cleanup old items if necessary
if (_box!.length > maxHistoryItems) {
await _cleanupOldItems();
}
}
}