【问题标题】:How to get current user inside a function that returns a stream如何在返回流的函数中获取当前用户
【发布时间】:2020-11-13 07:02:21
【问题描述】:
  1. 我有一个包含用户未付总额的文档。
  2. 我正在使用 StreamBuilder 收听此文档。
  3. 流是返回 Stream 的函数。

当我注册一个新用户时,我创建了一个字段为 int 0 的 totalUnpaid 文档。 紧接着,我导航到一个显示当前总未付金额的主页。 以前,我将当前用户硬编码为字符串。 现在我已经实现了 Firebase 身份验证,我希望主页显示新用户的 totalUnpaid。

以前,我的直播是这样的:

  static Stream<DocumentSnapshot> getTotalUnpaid(String currentUser) {
    final doc = Firestore.instance.collection(currentUser).document('totalUnpaid');
    return doc.snapshots();
  }

现在我创建了这个方法来获取我的当前用户:

  static Future<FirebaseUser> getCurrentUser() async {
    final FirebaseUser user = await FirebaseAuth.instance.currentUser();
    return user;
  }

如何在我的流中使用这个 Future? 我将不得不使用等待,这将要求函数是异步的,这将要求 Stream 成为未来,这将要求我的 StreamBuilder 成为 FutureBuilder。

这并不理想,因为每次用户添加商品时,totalUnpaid 都需要更新。

【问题讨论】:

    标签: firebase flutter dart google-cloud-firestore firebase-authentication


    【解决方案1】:

    您可以执行以下操作:

      static Stream<DocumentSnapshot> getTotalUnpaid() async*{
        final FirebaseUser user = await FirebaseAuth.instance.currentUser();
        final doc = Firestore.instance.collection(user.uid).document('totalUnpaid');
        yield* doc.snapshots();
      }
    

    当您将函数标记为async* 时,您可以使用yield*,它将返回来自Stream 的值。

    假设您使用 uid 作为集合名称,上述方法将起作用。

    【讨论】:

    • 完美运行。非常感谢哈达德
    猜你喜欢
    • 1970-01-01
    • 2017-11-25
    • 1970-01-01
    • 2021-10-23
    • 2012-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多