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.
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?
Here is my current code:
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)
});
}
Edit 1
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));
}
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!