我是扑朔迷离的新手,我想通过调用API从 InputField 转换一些文本。但是,我不想在每个按键时都调用它,而只是在用户暂停键入时才调用它。
I am new to flutter and I want to translate some text from an InputField by calling an API. However I don't want to call it on every key stroke, but instead only when the user paused typing.
在Android上,我只会使用 Handler 类,该类具有 postDelay(),并预先调用 removeAllCallbacksAndMessages(null)。有没有办法在Dart上做类似的事情?
On Android I would just use the Handler class with postDelay() with beforehand calling removeAllCallbacksAndMessages(null). Is there a way to do something similar on Dart?
这是我当前的代码:
Future<String> getTranslation(String query, Language from, Language to) async { // cancel here if a call to this function was less than 500 millis ago. return Future.delayed(const Duration(milliseconds: 500), () { return _translator.translate(query, from: from.code, to: to.code) }); }编辑1
我像这样从Bloc调用代码:
I'm calling the code from my Bloc like so:
@override Stream<State> mapEventToState(Event event) async* { if (event is QueryChangeEvent) { yield TextTranslationChangeState( query: event.query ?? "", translation: await _repo.getTranslation(event.query, currentState.fromLang, currentState.toLang)); }这就是为什么我不能调用 .then()的原因将来,因为我将无法从嵌套函数的块中产生新状态。
This is why I cannot call .then() on the future because I wouldn't be able to yield the new state from the block of the nested function.
任何帮助将不胜感激!
Any help is appreciated!
推荐答案您可以使用<$来取消 Future 异步操作c $ c> CancelableOperation 。
You can achieve cancelling the Future async operation by using CancelableOperation.
这里是一个示例(ps我简化了方法签名,以便于我轻松测试)
Here is an example (p.s I simplified your method signature for me to test it easily)
CancelableOperation cancellableOperation; Future<dynamic> fromCancelable(Future<dynamic> future) async { cancellableOperation?.cancel(); cancellableOperation = CancelableOperation.fromFuture(future, onCancel: () { print('Operation Cancelled'); }); return cancellableOperation.value; } Future<dynamic> getTranslation(String query, String from, String to) async { return Future.delayed(const Duration(milliseconds: 1000), () { return "Hello"; }); }在文本更改监听器上:
onTextChanged() { fromCancelable(getTranslation("query", "EN", "TR")).then((value) { print("Then called: $value"); }); }样本输出:
I/flutter ( 7312): Operation Cancelled I/flutter ( 7312): Operation Cancelled I/flutter ( 7312): Operation Cancelled I/flutter ( 7312): Operation Cancelled I/flutter ( 7312): Then called: Hello更多推荐
飞镖:取消发布延迟/将来
发布评论