简体   繁体   English

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

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

I have a code like below:我有如下代码:

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

How can I use "await" in this case?在这种情况下如何使用“等待”? I want when Timer ends then run next code below Timer.我想在 Timer 结束时运行 Timer 下面的下一个代码。 I used Future.delayed(), it can do it but I can't skip the delay time in Future.delayed() like in Timer().我使用了 Future.delayed(),它可以做到,但我不能像在 Timer() 中那样跳过 Future.delayed() 中的延迟时间。 Because i want to skip the delay time if the condition is true.因为如果条件为真,我想跳过延迟时间。 Because I want to skip the delay time if the condition is true.因为如果条件为真,我想跳过延迟时间。 If I use Future.delayed(), it doesn't have cancel() method like Timer().如果我使用 Future.delayed(),它没有像 Timer() 这样的 cancel() 方法。 Please tell me the solution.请告诉我解决方案。 Thanks谢谢

Try Future.delayed instead of Timer尝试 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");
}

When you wish to skip the timer just call timer cancel and the printWhenTimerEnds() method当您希望跳过计时器时,只需调用计时器取消和 printWhenTimerEnds() 方法

There are several ways to achieve what you need.有几种方法可以实现您所需要的。 You can useCompleter and Future.any like this:您可以像这样使用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());

Basically we are creating two futures one is a delayed and another one is cancelable future.基本上我们正在创建两个期货,一个是延迟的,另一个是可取消的未来。 And we are waiting for the first one that completes using Future.any .我们正在等待使用Future.any完成的第一个。

The other option is to use CancelableOperation or CancelableCompleter .另一种选择是使用CancelableOperationCancelableCompleter

For example:例如:

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.');
});

Here we do practically the same thing as above but with already available classes.在这里,我们实际上做了与上面相同的事情,但已经有了可用的类。 We are wrapping Future.delayed into CancelableOperation so we are able now to cancel that operation ( Future.delayed in our case).我们将Future.delayed包装到CancelableOperation中,因此我们现在可以取消该操作(在我们的例子中是Future.delayed )。

Another way you can wrap Timer into future with Completer and so on.您可以使用Completer等将Timer包装到未来的另一种方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM