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

标签 api dart flutter textfield throttling

如果我有一个文本字段,并且在该文本字段发生变化时,我会调用一个调用 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/

相关文章:

api - UPS 运输 REST API

firebase - 检查Firebase文档中的特定字段,如果找到字段,则返回文档ID。

dart - 在TextFormField中插入Dash

Flutter:如何更改幻灯片上的选项卡图标颜色,而不仅仅是点击?

flutter - 如何在Flutter插件中获取事件和上下文

objective-c - 以编程方式访问 Apple 应用商店

web-services - 在 RallyDev API v2.0 中使用 HeirarchicalRequirements 和缺陷获取任务名称/ID

php - 通过将用户的ID +时间加密为JSON来创建访问 token

ios - Flutter 找不到方法的原生 iOS 实现

Flutter firebase_admob 横幅仍然显示在每个屏幕上