实时搜索:在用户输入完

时间:2020-04-11 12:22:16

标签: flutter flutter-provider flutter-http

在我的应用程序中,当用户在TextField中键入内容时,我正在搜索结果。我使用的是提供程序,其中存在每次用户在文本字段中键入内容时都会触发的searchProduct()函数。获取结果后,我将调用notifyListener()函数,并且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();
    }
  }
}

1 个答案:

答案 0 :(得分:1)

用户https://cloud.google.com/monitoring/kubernetes-engine/migration并设置倒计时的持续时间,例如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();
  }
}