首页 > 解决方案 > 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(_) {
 }   

}

标签: restsearchfluttersearchbar

解决方案


不知道它是否仍然有用,但我使用 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(_) {
 }   

}

推荐阅读