dart - 增加构建 future 的延迟

标签 dart

与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/

相关文章:

dart - 如何动态翻译应用程序

dart - ListView 中的按钮溢出

flutter - AnimatedContainer-如何只展开一个,其余的留在下面?

android - flutter 。使用主题,如何更改滚动偏移颜色?

Flutter - 有没有办法查看哪一行代码抛出错误?

flutter - VS 代码不会在调试控制台中显示 Flutter 错误

firebase - 来自 Flutter 中 firebase_auth 插件的更多用户数据

dart - Flutter - 总是在页面出现时执行一个函数

dart - Navigator routes 清除flutter的堆栈

android - 出现错误;没有为类型 '[]' 定义运算符 'Object? Function()'