Flutter 颤振延迟后的返回代码结果?
我正在尝试运行这个Future函数,它在500毫秒过去后运行计时器。我遇到的问题是计时器没有将数据传递给results变量,因此_destinationOnSearchChanged()最终返回null 注:Flutter 颤振延迟后的返回代码结果?,flutter,dart,Flutter,Dart,我正在尝试运行这个Future函数,它在500毫秒过去后运行计时器。我遇到的问题是计时器没有将数据传递给results变量,因此_destinationOnSearchChanged()最终返回null 注:getCity(上下文,\u typeAheadController.text)返回数据,但仅在计时器函数内返回 Future _destinationOnSearchChanged() async { dynamic results; //Ca
getCity(上下文,\u typeAheadController.text)代码>返回数据,但仅在计时器函数内返回
Future _destinationOnSearchChanged() async {
dynamic results;
//Cancels timer if its still running
if (_apiCityThrottle?.isActive ?? false) {
_apiCityThrottle.cancel();
}
//Makes API call half a second after last typed button
_apiCityThrottle = Timer(const Duration(milliseconds: 500), () async{
results = await getCity(context, _typeAheadController.text);
});
print(results);
return await results;
}
,您可能应该研究现有的去盎司机制,而不是创建自己的机制
如果您仍然想沿着这条路径前进:您的问题是创建一个计时器
,然后立即返回结果
。您不必等待计时器
启动(也不能直接等待计时器
)。在这种情况下,您可以使用:
Future\u destinationOnSearchChanged()异步{
var timerCompleter=Completer();
//如果计时器仍在运行,则取消计时器。
_apiCityThrottle?.cancel();
//在上次键入按钮后半秒进行API调用。
_apiCityThrottle=计时器(常量持续时间(毫秒:500),()异步{
timerCompleter.complete(等待getCity(上下文,_typeAheadController.text));
});
var results=await timerCompleter.complete();
打印(结果);
返回结果;
}
如果您想在键入某些查询字符串时延迟半秒来调用API,那么使用Flatter的Stream
API`和方法会更容易