Flutter-解决搜索时数据错乱的问题

《Flutter-解决搜索时数据错乱的问题》

春风得意马蹄疾
一日看尽长安花

前言

《Flutter-解决搜索时数据错乱的问题》

问题描述
搜索框中快速输入和删除文本时,在不停的发送网络请求

问题解决
解决发送多条网络请求,数据回调正常

解决思路

利用iOS中搜索的思想,
在每个网络请求中带上搜索的keyword
把keyword当作搜索结果model的属性
在每次的model返回时判断当前的属性和最后一次的搜索keyword是否一致
一致就刷新数据,否则就丢弃数据

代码实现

    // 输入框的改变事件
    _onSearch(String text) {
        // _searchText全局的属性,用来保存每次搜索输入的内容
        _searchText = text;
        if (text == null || text.isEmpty) { // 如果没有搜索内容为空则把数据源置为空
          _searchResult = [];
          setState(() {});
        } else {// 如果有搜索内容则发送网络请求
          fetchSearchSuggestionData(text);
        }
      }
      // 发送网络请求
      Future fetchSearchSuggestionData(String keyward) async {
        await SearchSuggestionDao.fetchSearchSuggestion('', keyward).then((model) {
          // 判断每次搜索回调的数据key和最后一次的搜索_searchText是否一致 (重点)
          if (model.keyword == _searchText) {
            _searchResult = model.districtAndLandmark;
            setState(() {});
          } // 防止数据错乱
        });
      }
      
      
      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;// 在搜索model中保存搜索key
            return model;
          } catch (error) {
            return null;
          }
        } else {
          return null;
        }
      }
    原文作者:Jieyi
    原文地址: https://segmentfault.com/a/1190000020257041
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞