简体   繁体   English

更改TextField,调用api - 如何限制它?

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

If I have a textfield, and on change in that textfield, I call a function, which calls an API, how can I throttle that, so it calls that function only if user has not typed anything for 1 second? 如果我有一个文本字段,并且在该文本字段中进行更改,我调用一个调用API的函数,我该如何限制它,所以只有当用户没有键入任何内容1秒钟时才会调用该函数?

Im lost here.. any help is more than welcome. 我迷失在这里..任何帮助都非常受欢迎。

Use a Timer . 使用Timer

If a key is pressed before one second cancel the old timer and reschedule with a new Timer, otherwise make the API call: 如果在一秒钟之前按下一个键取消旧计时器并使用新的计时器重新计划,否则进行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')),
            ),
          ],
        ),
      ),
    );
  }
}

You need to make use of a class named CancelableOperation from the async package . 您需要从异步包中使用名为CancelableOperation的类。

You can declare it in your stateful widget, outside the build() method: 您可以在build()方法之外的有状态窗口小部件中声明它:

CancelableOperation cancelableOperation;

And use it like so within your onChanged callback: 并在你的onChanged回调中使用它:

cancelableOperation?.cancel();

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM