Дарт: отменяемая задержка / будущее - PullRequest
0 голосов
/ 28 мая 2019

Я плохо знаком с флаттером и хочу перевести некоторый текст из InputField, вызвав API.Однако я не хочу вызывать его при каждом нажатии клавиши, а вместо этого, только когда пользователь приостановил набор текста.

В Android я бы просто использовал класс Handler с postDelay() с предварительным вызовом removeAllCallbacksAndMessages(null),Есть ли способ сделать что-то похожее на Дарт?

Вот мой текущий код:

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

Я звонюкод из моего Блока примерно так:

@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() в будущем, потому что я не смог бы получить новое состояние из блока вложенной функции.

Любая помощь приветствуется!

Ответы [ 3 ]

2 голосов
/ 28 мая 2019

Да, есть, он называется Таймер

https://api.dartlang.org/stable/2.3.1/dart-async/Timer-class.html

Вы можете отложить выполнение, а также отменить триггер.

1 голос
/ 28 мая 2019

Отменить асинхронную операцию Future можно, используя CancelableOperation.

Вот пример (p.s я упростил подпись вашего метода, чтобы я мог его легко проверить)

  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
0 голосов
/ 28 мая 2019

Предполагая, что вы используете TextField для ввода, вы можете позвонить getTranslation() на onSubmitted, который будет вызван, когда пользователь закончит редактирование:

 TextField(
   onSubmitted: (value) {
     getTranslation(value, 'en', 'ru'); 
   },
 );
...