rest - Flutter:搜索栏-延迟后向服务器发送请求
问题描述
我有一个搜索栏,它会在用户输入内容 1 秒后进行休息呼叫。但是,如果用户输入更多的字母,例如“asd”,实际上它会执行 3 个请求,一个用于“a”,一个用于“s”,一个用于“d”。当用户停止时,有没有办法只打一个电话?
代码是:
appBarTitle = new TextField(
controller: _filterController,
decoration: new InputDecoration(
hintText: 'Search...'
)
);
_filterController.addListener(() {
if (_filterController.text.isEmpty) {
} else {
Future.delayed(Duration(seconds: 1), () {
userWrites(_filterController.text);
});
}
});
userWrites(String filterName){
try {
//TODO: call
}catch(_) {
}
}
解决方案
不知道它是否仍然有用,但我使用 Timer 类解决了它。
Timer timer;
appBarTitle = new TextField(
controller: _filterController,
decoration: new InputDecoration(
hintText: 'Search...'
)
);
_filterController.addListener(() {
if (_filterController.text.isEmpty) {
} else {
if(timer != null){
timer.cancel();
timer = null;
}
timer = Timer(Duration(seconds: 1), userWrites);
}
});
userWrites(){
try {
print(_filterController.text);
//TODO: call
}catch(_) {
}
}
推荐阅读
- python - 将多个py更改为exe
- elixir - 如果 ecto 的 preload 为零,则创建空的 has_one 关联
- python - 在多个进程之间共享 Python dict
- python - Pyrebase:从第二个 get().val() 返回 None
- ssis - 打开 Biml 解决方案崩溃 VS2019
- android - 调试正常时无法构建发布 APK
- c++ - 尝试使用 Emscripten 构建 C++ SDL2 项目时未定义的符号
- r - 从单独的数据框列表中的列表中的数据框中提取列
- android - Kotlin - 与 Recyclerview 滚动同步移动视图
- javascript - 如何更改下面的 javascript 代码,以便我的 div 样式切换从显示无开始到显示网格?