【问题标题】:Convert a Stream to a Future in Flutter在 Flutter 中将 Stream 转换为 Future
【发布时间】:2020-11-03 13:51:02
【问题描述】:

这里是 Flutter 初学者,所以如果我的问题很愚蠢,请不要介意...

如何将 Stream 转换为 Future?

我有一个 Stream,它只是多次调用请求的 URL,因为它是一个 Stream。我希望能够获取数据而不是加载状态...因为我总是永远加载

在某处是否有类似Future.fromStream() 的函数而我错过了它?

我能做到吗?

我没有提供任何代码,因为如果您需要代码,我认为不需要,我可以编辑问题

【问题讨论】:

    标签: flutter dart futuretask


    【解决方案1】:

    StreamfirstWhere 方法,这将返回 Future

    _profileService.profileStream.firstWhere((element) => false);
    

    【讨论】:

      【解决方案2】:

      Stream 和 Future 是两个不同的概念。

      在您使用时,流会保持数据更新,而 Future 只是一次。 使用流的示例:购物车、商品列表 使用future的例子:登录后getUserDetails。

      如果您使用的是流,那么您可以使用 streambuilder 来构建您的 UI

      StreamBuilder<User>(
        stream: userBloc.author, // your stream here
        builder:
            (BuildContext context, AsyncSnapshot<User> snapshot) {
          if (snapshot.connectionState == ConnectionState.active && snapshot.hasData) {
            // do your work here
          } else {
            return CircularprogressIndicator();
          }
        },
      )
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-03-25
        • 1970-01-01
        • 2020-10-02
        • 2020-04-16
        • 2023-01-03
        • 1970-01-01
        • 2020-09-02
        相关资源
        最近更新 更多