如果我有一个文本框,并且在该文本框中更改时,我调用一个函数,该函数调用一个API,如何进行节流,以便仅在用户没有输入任何内容的情况下才调用该函数1秒钟?
我在这里迷失了..任何帮助都将不胜感激。
如果我有一个文本框,并且在该文本框中更改时,我调用一个函数,该函数调用一个API,如何进行节流,以便仅在用户没有输入任何内容的情况下才调用该函数1秒钟?
我在这里迷失了..任何帮助都将不胜感激。
使用Timer
。
如果在1秒钟内按下键,则取消旧计时器并使用新计时器重新安排,否则进行API调用:
import 'dart:async';
class _MyHomePageState extends State<MyHomePage> {
String textValue;
Timer timeHandle;
void textChanged(String val) {
textValue = val;
if (timeHandle != null) {
timeHandle.cancel();
}
timeHandle = Timer(Duration(seconds: 1), () {
print("Calling now the API: $textValue");
});
}
@override
void dispose() {
super.dispose();
timeHandle.cancel();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Container(
padding: EdgeInsets.all(20),
alignment: Alignment.center,
child: TextField(
onChanged: textChanged,
decoration: InputDecoration(
border: InputBorder.none,
hintText: 'Please enter a search term')),
),
],
),
),
);
}
}
CancelableOperation
类。你可以在你的有状态小部件中声明它,放在build()
方法之外:CancelableOperation cancelableOperation;
在onChanged
回调中使用它的方式如下:
最初的回答:
cancelableOperation?.cancel();
cancelableOperation = CancelableOperation.fromFuture(Future.delayed(Duration(seconds: 1), () {
// API call here
}));