如何在Flutter中基于未来结果构建流? [英] How to build a Stream based on a Future result in Flutter?

查看:55
本文介绍了如何在Flutter中基于未来结果构建流?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Flutter应用程序,它使用Firebase存储和google登录。
我尝试执行的步骤非常简单:

I have a Flutter app which uses Firebase-storage and google-signin. the steps I am trying to do is so simple:

1-使用Google登录(完成)。

1- Sign-in using Google (Done).

2-获取当前用户ID(完成)。

2- Get Current User Id (Done).

3-为流构建器构建流时使用用户ID(问题)。

3- Use the User Id when construct the stream for the stream builder (the problem).

到目前为止,我正在使用 Future 来获取当前用户ID,
然后将用户ID注入 Where子句

what I did so far is that I am using a Future to get the Current User Id, then to inject the user Id inside the Where clause

.where('userId ',isEqualTo:userId)

这就是我最终得到的结果:

and this is what I end up with:

这是我应该创建流的部分:

this is the part where I should create the stream:

  // Get document's snapshots and return it as stream.
  Future<Stream> getDataStreamSnapshots() async {
    // Get current user.
    final User user = await FirebaseAuth().currentUser();
    String userId = user.uid;

    Stream<QuerySnapshot> snapshots =
      db
        .collection(db)
        .where("uid", isEqualTo: userId)
        .snapshots();

    try {
      return snapshots;
    } catch(e) {
      print(e);
      return null;
    }
  }

这是我应该致电和接收的部分流中,

and this is the part where should I call and receive the stream,

...
children: <Widget>[
    StreamBuilder<QuerySnapshot>(
          stream: CALLING THE PREVIOUS FUNCTION,
            builder: (BuildContext context, 
                      AsyncSnapshot<QuerySnapshot> snapshot) {
                if (snapshot.hasData) {
                    ...
                }
              ...

但是此代码不起作用,因为我无法获得Future应该返回的值?有什么想法吗?

But this code does not work, because I am not able to get the value that should returned by the Future? any idea?

非常感谢

推荐答案

您永远不应拥有 Future< Stream> ,即双异步性,只需返回 Stream ,然后在准备就绪之前不必发出任何事件。

You should never have a Future<Stream>, that's double-asynchrony, which is unnecessary. Just return a Stream, and then you don't have to emit any events until you are ready to.

尚不清楚 try / catch 在保护什么因为返回非 Future 无法返回。如果返回流,也将在流上发出任何错误。

It's not clear what the try/catch is guarding because a return of a non-Future cannot throw. If you return a stream, just emit any error on the stream as well.

您可以将代码重写为:

Stream<QuerySnapshot> getDataStreamSnapshots() async* {
  // Get current user.
  final User user = await FirebaseAuth().currentUser();
  String userId = user.uid;

  yield* db
    .collection(db)
    .where("uid", isEqualTo: userId)
    .snapshots();
}

一个 async * 函数是异步的,因此可以使用 await 。它返回 Stream ,并使用 yield事件在流中发出事件; yield * streamOfEvents;

An async* function is asynchronous, so you can use await. It returns a Stream, and you emit events on the stream using yield event; or yield* streamOfEvents;.

这篇关于如何在Flutter中基于未来结果构建流?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆