飞镖:取消发布延迟/将来

编程入门 行业动态 更新时间:2024-10-28 07:30:12
本文介绍了飞镖:取消发布延迟/将来的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我是扑朔迷离的新手,我想通过调用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

更多推荐

飞镖:取消发布延迟/将来

本文发布于:2023-10-11 17:54:26,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1482408.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:飞镖   将来

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!