TextField 发生变化,调用 api - 如何限制它?

TextField on change, call api - how to throttle this?

如果我有一个文本字段,并且在该文本字段发生变化时,我会调用一个函数,该函数会调用一个 API,我该如何限制它,以便它仅在用户未输入任何内容时调用该函数1 秒?

我迷路了..非常欢迎任何帮助。

您需要使用 async package 中名为 CancelableOperation 的 class。

您可以在 build() 方法之外的有状态小部件中声明它:

CancelableOperation cancelableOperation;

并在您的 onChanged 回调中像这样使用它:

cancelableOperation?.cancel();

cancelableOperation = CancelableOperation.fromFuture(Future.delayed(Duration(seconds: 1), () {
  // API call here
}));

使用 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')),
            ),
          ],
        ),
      ),
    );
  }
}