与Dart一起玩,是否有可能在构建Future时造成延迟?
Future<String>.value("Hello").then((newsDigest) {
print(newsDigest);
}) // .delayed(Duration(seconds: 5))
是的,这是可能的:
factory Future.delayed(Duration duration, [FutureOr<T> computation()]) {
_Future<T> result = new _Future<T>();
new Timer(duration, () {
try {
result._complete(computation?.call());
} catch (e, s) {
_completeWithErrorCallback(result, e, s);
}
});
return result;
}
最佳答案
您已经发现Future.delayed
构造函数创建了一个在延迟后运行的Future:
从docs:
Future<T>.delayed(
Duration duration,
[ FutureOr<T> computation()
])
The computation will be executed after the given duration has passed, and the future is completed with the result of the computation.
If computation returns a future, the future returned by this constructor will complete with the value or error of that future.
为了简单起见,以一个立即完成并带有值的 future 为例,此摘要创建了一个延迟的 future ,该延迟在3秒后完成:
import 'dart:async';
main() {
var future = Future<String>.value("Hello");
var delayedFuture = Future.delayed(Duration(seconds: 3), () => future);
delayedFuture.then((value) {
print("Done: $value");
});
}
关于dart - 增加构建 future 的延迟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53802614/