如何在飞镖/长笛中一起使用定时器和等待



我有一个如下代码:

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

我如何使用";等待";在这种情况下?我想当定时器结束,然后运行定时器下面的下一个代码。我使用了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');

有几种方法可以满足您的需求。您可以像这样使用Completer和Future.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的程序。

另一个选项是使用CancelableOperation或CancelableCompleter。

例如:

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封装到未来

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

当您希望跳过计时器时,只需调用计时器取消和printWhenTimerEnd((方法

最新更新