实时搜索:用户输入完毕后开始搜索

2024-03-31

在我的应用程序中,当用户在文本字段中键入内容时,我正在搜索结果。我正在使用 Provider,其中有一个 searchProduct() 函数,每次用户在文本字段中键入内容时都会触发该函数。获取结果后,我将调用 notificationListener() 函数,并且 UI 会相应更新。

我面临的问题是,由于结果是异步获取的,因此它们不会同时到达。有时最后一个结果出现在之前的结果之一之前。当用户输入太快时尤其会发生这种情况。因此,每次击键都会调用此 searchProduct() 函数并发出网络请求。这种方法也会产生太多不必要的网络请求,这并不理想。 解决此问题的最佳方法是什么,以便在用户输入搜索字符串的给定时间内,搜索将在用户输入完毕后开始?

class ProductService extends ChangeNotifier {
  String _searchText;

  String serverUrl = 'https://api.example.com/api';

  String get searchText => _searchText;
  List<Product> products = [];
  bool searching = false;

  void searchProduct(String text) async {
    searching = true;
    notifyListeners();
    _searchText = text;

    var result = await http
        .get("$serverUrl/product/search?name=$_searchText");
    if (_searchText.isEmpty) {
      products = [];
      notifyListeners();
    } else {
      var jsonData = json.decode(result.body);

      List<Map<String, dynamic>> productsJson =
          List.from(jsonData['result'], growable: true);
      if (productsJson.length == 0) {
        products = [];
        notifyListeners();
      } else {
        products = productsJson
            .map((Map<String, dynamic> p) => Product.fromJson(p))
            .toList();
      }
      searching = false;
      notifyListeners();
    }
  }
}

User 可重启定时器 https://pub.dev/documentation/async/latest/async/RestartableTimer-class.html并将倒计时的持续时间设置为 2 秒。用户第一次键入字符时,计时器将初始化,然后每次键入字符时,计时器都会重置。如果用户停止输入 2 秒,包含网络请求的回调将会触发。显然,代码需要改进以考虑其他情况,例如,如果请求在出于某种原因触发之前应被取消。

TextField(
      controller: TextEditingController(),
      onChanged: _lookupSomething,
);


RestartableTimer timer;
static const timeout = const Duration(seconds: 2);

_lookupSomething(String newQuery) {

  // Every time a new query is passed as the user types in characters
  // the new query might not be known to the callback in the timer 
  // because of closures. The callback might consider the first query that was
  // passed during initialization. 
  // To be honest I don't know either if referring to tempQuery this way
  // will fix the issue.  

  String tempQuery = newQuery;

  if(timer == null){
    timer = RestartableTimer(timeout, (){
      myModel.search(tempQuery);
    });
  }else{
    timer.reset();
  }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

实时搜索:用户输入完毕后开始搜索 的相关文章

随机推荐