实时搜索:在用户完成键入后开始搜索



在我的应用程序中,当用户在TextField中键入内容时,我正在搜索结果。我使用的Provider中有一个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();
}
}
}

User RestartableTimer并将倒计时的持续时间设置为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();
}
}

最新更新