Flutter to solve the problem of data disorder in search

Time:2021-3-3

Flutter to solve the problem of data disorder in search

Horse’s hoof disease
See Chang’an flowers in one day

preface

Flutter to solve the problem of data disorder in search

Problem description
Search box to quickly enter and delete text, constantly send network requests

Problem solving
Solve sending multiple network requests, data callback is normal

Solutions

Using the idea of search in IOS,
Bring the search keyword in each network request
Regard keyword as the attribute of search result model
Each time the model returns, judge whether the current attribute is consistent with the last search keyword
If it is consistent, refresh the data, otherwise discard the data

code implementation

//Input box change events
    _onSearch(String text) {
        // _ Searchtext global property, used to save the content of each search input
        _searchText = text;
        if (text == null ||  text.isEmpty ){// if no search content is empty, set the data source to null
          _searchResult = [];
          setState(() {});
        }Else {// if there is search content, send a network request
          fetchSearchSuggestionData(text);
        }
      }
      //Send network request
      Future fetchSearchSuggestionData(String keyward) async {
        await SearchSuggestionDao.fetchSearchSuggestion('', keyward).then((model) {
          //Judge the data key of each search callback and the last search_ Is searchtext consistent (key)
          if (model.keyword == _searchText) {
            _searchResult = model.districtAndLandmark;
            setState(() {});
          }// prevent data disorder
        });
      }
      
      
      static Future<SearchSuggestionModel> fetchSearchSuggestion(String cityId,String keyWord) async {
        Response response =
            await DioGo.get(Url.getUrl(SearchSuggestionUrl), params: {'cityId': cityId,'keyWord': keyWord});
        if (response.isSuccess() && response.data != null) {
          try {
            SearchSuggestionModel model =
                SearchSuggestionModel.fromJson(response.data['content']);
            model.keyword  =Keyword; // save the search key in the search model
            return model;
          } catch (error) {
            return null;
          }
        } else {
          return null;
        }
      }