1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374 |
- import 'dart:math';
- import 'package:flutter/material.dart';
- import 'package:shared_preferences/shared_preferences.dart';
- import 'package:sport/services/api/inject_api.dart';
- enum SearchBody {
- defaultBody,
- suggestions,
- results,
- }
- class SearchModel with ChangeNotifier, InjectApi {
- SearchBody _currentBody = SearchBody.defaultBody;
- SearchBody get currentBody => _currentBody;
- void updateCurrentBody(SearchBody value) {
- _currentBody = value;
- notifyListeners();
- }
- var _searchValue = '';
- List<String> hot = [];
- List<String> history = [];
- String get searchValue => _searchValue;
- final String PREF_KEY = "searchHistory";
- void updateSearchValue(String searchValue) {
- this._searchValue = searchValue;
- notifyListeners();
- updateCurrentBody(this._searchValue.isNotEmpty
- ? SearchBody.suggestions
- : SearchBody.defaultBody);
- }
- void queryValue(String value) async {
- SharedPreferences prefs = await SharedPreferences.getInstance();
- if (history == null) history = [];
- if (!history.contains(value)) {
- List<String> items = history
- ..insert(0, value)
- ..sublist(0, min(10, history.length));
- prefs.setStringList(PREF_KEY, items);
- }
- _searchValue = value;
- updateCurrentBody(SearchBody.results);
- }
- void suggestionValue(String value) {
- updateCurrentBody(SearchBody.suggestions);
- }
- void getHistory() async {
- SharedPreferences prefs = await SharedPreferences.getInstance();
- history = prefs.getStringList(PREF_KEY) ?? [];
- notifyListeners();
- }
- void getHot() async {
- hot = (await api.getSearchWords()).results;
- hot.shuffle();
- notifyListeners();
- }
- void clearHistory() async {
- SharedPreferences prefs = await SharedPreferences.getInstance();
- prefs.setStringList(PREF_KEY, []);
- history = [];
- notifyListeners();
- }
- }
|