如果我有一个文本字段,并且在该文本字段发生变化时,我会调用一个调用 API 的函数,我如何限制它,以便它仅在用户 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')),
),
],
),
),
);
}
}
关于api - TextField 发生变化,调用 api - 如何限制这个?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54765307/