import 'dart:convert'; import 'package:shared_preferences/shared_preferences.dart'; import '../../../utils/tools/app_sp.dart'; /// 本地搜索历史(SharedPreferences),key 与 [AppSp] 规则一致(`.search.history`)。 class SearchUtil { SearchUtil._(); static const String _storageKey = 'sky.search.history'; static const int _maxHistory = 20; static Future> _readList(SharedPreferences prefs) async { final raw = prefs.getString(_storageKey); if (raw == null || raw.isEmpty) return []; try { final decoded = jsonDecode(raw); if (decoded is! List) return []; return decoded.map((e) => e.toString()).where((s) => s.isNotEmpty).toList(); } catch (_) { return []; } } static Future _writeList(SharedPreferences prefs, List list) async { await prefs.setString(_storageKey, jsonEncode(list)); } /// 查询搜索历史列表(新记录在前)。 static Future> getSearchList() async { final prefs = await AppSp.getInstance(); return _readList(prefs); } /// 添加一条搜索;去重、去空白,并移到最前。 static Future addSearch(String keyword) async { final q = keyword.trim(); if (q.isEmpty) return; final prefs = await AppSp.getInstance(); final list = await _readList(prefs); list.removeWhere((e) => e == q); list.insert(0, q); if (list.length > _maxHistory) { list.removeRange(_maxHistory, list.length); } await _writeList(prefs, list); } /// 删除单条搜索记录。 static Future deleteSearch(String keyword) async { final prefs = await AppSp.getInstance(); final list = await _readList(prefs); list.removeWhere((e) => e == keyword); await _writeList(prefs, list); } /// 清空全部搜索历史。 static Future clearAllSearch() async { final prefs = await AppSp.getInstance(); await prefs.remove(_storageKey); } }