簡體   English   中英

如何在 Dart/Flutter 中同時使用 Timer 和 await?

[英]How to use Timer and await together in Dart/Flutter?

我有如下代碼:

Timer(Duration(seconds: 5),(){
   print("This is printed after 5 seconds.");
});
print("This is printed when Timer ends");

在這種情況下如何使用“等待”? 我想在 Timer 結束時運行 Timer 下面的下一個代碼。 我使用了 Future.delayed(),它可以做到,但我不能像在 Timer() 中那樣跳過 Future.delayed() 中的延遲時間。 因為如果條件為真,我想跳過延遲時間。 因為如果條件為真,我想跳過延遲時間。 如果我使用 Future.delayed(),它沒有像 Timer() 這樣的 cancel() 方法。 請告訴我解決方案。 謝謝

嘗試 Future.delayed 而不是 Timer

await Future.delayed(Duration(seconds: 5),(){

                print("This is printed after 5 seconds.");
              });

              print('This is printed when Timer ends');
Timer(Duration(seconds: 5),(){
   print("This is printed after 5 seconds.");
   printWhenTimerEnds();
});

void printWhenTimerEnds(){
 print("This is printed when Timer ends");
}

當您希望跳過計時器時,只需調用計時器取消和 printWhenTimerEnds() 方法

有幾種方法可以實現您所需要的。 您可以像這樣使用CompleterFuture.any

import 'dart:async';

Completer<void> cancelable = Completer<void>();

// auxiliary function for convenience and better code reading
void cancel() => cancelable.complete();

Future.any(<Future<dynamic>>[
  cancelable.future,
  Future.delayed(Duration(seconds: 5)),
]).then((_) {
  if (cancelable.isCompleted) {
    print('This is print when timer has been canceled.');
  } else {
    print('This is printed after 5 seconds.');
  }
});

// line to test cancel, comment to test timer completion
Future.delayed(Duration(seconds: 1)).then((_) => cancel());

基本上我們正在創建兩個期貨,一個是延遲的,另一個是可取消的未來。 我們正在等待使用Future.any完成的第一個。

另一種選擇是使用CancelableOperationCancelableCompleter

例如:

import 'dart:async';
import 'package:async/async.dart';

Future.delayed(Duration(seconds: 1)).then((_) => cancel());

var cancelableDelay = CancelableOperation.fromFuture(
  Future.delayed(Duration(seconds: 5)),
  onCancel: () => print('This is print when timer has been canceled.'),
);

// line to test cancel, comment to test timer completion
Future.delayed(Duration(seconds: 1)).then((_) => cancelableDelay.cancel());

cancelableDelay.value.whenComplete(() {
  print('This is printed after 5 seconds.');
});

在這里,我們實際上做了與上面相同的事情,但已經有了可用的類。 我們將Future.delayed包裝到CancelableOperation中,因此我們現在可以取消該操作(在我們的例子中是Future.delayed )。

您可以使用Completer等將Timer包裝到未來的另一種方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM