search_model.dart 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. import 'dart:math';
  2. import 'package:flutter/material.dart';
  3. import 'package:shared_preferences/shared_preferences.dart';
  4. import 'package:sport/services/api/inject_api.dart';
  5. enum SearchBody {
  6. defaultBody,
  7. suggestions,
  8. results,
  9. }
  10. class SearchModel with ChangeNotifier, InjectApi {
  11. SearchBody _currentBody = SearchBody.defaultBody;
  12. SearchBody get currentBody => _currentBody;
  13. void updateCurrentBody(SearchBody value) {
  14. _currentBody = value;
  15. notifyListeners();
  16. }
  17. var _searchValue = '';
  18. List<String> hot = [];
  19. List<String> history = [];
  20. String get searchValue => _searchValue;
  21. final String PREF_KEY = "searchHistory";
  22. void updateSearchValue(String searchValue) {
  23. this._searchValue = searchValue;
  24. notifyListeners();
  25. updateCurrentBody(this._searchValue.isNotEmpty ? SearchBody.suggestions : SearchBody.defaultBody);
  26. }
  27. void queryValue(String value) async {
  28. SharedPreferences prefs = await SharedPreferences.getInstance();
  29. if (history == null) history = [];
  30. if (!history.contains(value)) {
  31. List<String> items = history
  32. ..insert(0, value)
  33. ..sublist(0, min(10, history.length));
  34. prefs.setStringList(PREF_KEY, items);
  35. }
  36. _searchValue = value;
  37. updateCurrentBody(SearchBody.results);
  38. }
  39. void suggestionValue(String value) {
  40. updateCurrentBody(SearchBody.suggestions);
  41. }
  42. void getHistory() async {
  43. SharedPreferences prefs = await SharedPreferences.getInstance();
  44. history = prefs.getStringList(PREF_KEY);
  45. notifyListeners();
  46. }
  47. void getHot() async {
  48. hot = (await api.getSearchWords()).results;
  49. hot?.shuffle();
  50. notifyListeners();
  51. }
  52. void clearHistory() async {
  53. SharedPreferences prefs = await SharedPreferences.getInstance();
  54. prefs.setStringList(PREF_KEY, []);
  55. history = [];
  56. notifyListeners();
  57. }
  58. }