search_model.dart 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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
  26. ? SearchBody.suggestions
  27. : SearchBody.defaultBody);
  28. }
  29. void queryValue(String value) async {
  30. SharedPreferences prefs = await SharedPreferences.getInstance();
  31. if (history == null) history = [];
  32. if (!history.contains(value)) {
  33. List<String> items = history
  34. ..insert(0, value)
  35. ..sublist(0, min(10, history.length));
  36. prefs.setStringList(PREF_KEY, items);
  37. }
  38. _searchValue = value;
  39. updateCurrentBody(SearchBody.results);
  40. }
  41. void suggestionValue(String value) {
  42. updateCurrentBody(SearchBody.suggestions);
  43. }
  44. void getHistory() async {
  45. SharedPreferences prefs = await SharedPreferences.getInstance();
  46. history = prefs.getStringList(PREF_KEY) ?? [];
  47. notifyListeners();
  48. }
  49. void getHot() async {
  50. hot = (await api.getSearchWords()).results;
  51. hot.shuffle();
  52. notifyListeners();
  53. }
  54. void clearHistory() async {
  55. SharedPreferences prefs = await SharedPreferences.getInstance();
  56. prefs.setStringList(PREF_KEY, []);
  57. history = [];
  58. notifyListeners();
  59. }
  60. }