baw*_*wsi 2 api throttling textfield dart flutter
如果我有一个文本字段,并且在该文本字段中进行了更改,那么我会调用一个函数,该函数会调用一个API,如何限制它,因此仅当用户在1秒钟内未键入任何内容时,它才会调用该函数?
我在这里迷路了..任何帮助都超过了欢迎。
使用Timer。
如果在一秒钟之前按了一个键,则取消旧计时器并使用新计时器重新安排时间,否则进行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')),
),
],
),
),
);
}
}
Run Code Online (Sandbox Code Playgroud)
您需要使用async 包CancelableOperation中命名的类。
您可以在有状态小部件中的方法外部声明它build():
CancelableOperation cancelableOperation;
Run Code Online (Sandbox Code Playgroud)
并在回调中像这样使用它onChanged:
cancelableOperation?.cancel();
cancelableOperation = CancelableOperation.fromFuture(Future.delayed(Duration(seconds: 1), () {
// API call here
}));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
319 次 |
| 最近记录: |