简体   繁体   English

引用列表上的Flutter Firestore StreamBuilder

[英]Flutter Firestore StreamBuilder on list of references

The Firestore database is build of one collection of users. Firestore数据库由一组用户构成。 Every user document has some public data and a array of users ID's that he follows called following. 每个用户文档都有一些公共数据和他遵循的称为“跟随”的用户ID数组。 In the Flutter app I would like to create a StreamBuilder on the following array. 在Flutter应用中,我想在以下数组上创建一个StreamBuilder。 So when the user adds someone to his following array - it would be added to the stream, and when a user from the following list changes his data - the stream would update too. 因此,当用户将某人添加到他的后续数组中时(该数组将添加到流中),并且当以下列表中的用户更改其数据时,该流也将更新。

I thought maybe to use a list of references ( 'users/usersid3' ) instead of a list of IDs ( 'userid3' ), but I don't know how to implement it. 我以为可能使用引用列表( 'users/usersid3' )而不是ID列表( 'userid3' ),但是我不知道如何实现它。

This is how the database is structured. 这就是数据库的结构方式。

users
      - user1id
            - some public data
            - following: [user2id, user3id]
      - user2id
            - some public data
            - following: []
      - user3id
            - some public data
            - following: [user2id]

So, there is a workaround to solve this problem. 因此,有一种解决方法来解决此问题。

  1. I saved the following list as map (named 'followingMap') in a separate document 'followingDoc'). 我将以下列表另存为地图(名为“ followingMap”)在单独的文档“ followingDoc”中。
  2. Used a StreamBuilder on that document: 在该文档上使用了StreamBuilder:
StreamBuilder(
  stream: Firestore.instance.collection('users').document(uid).collection('data').document('followingDoc').snapshots(),
  builder: (context, snapshot) {
    if (!snapshot.hasData) return Text("No data");
    return ListView.builder(
      itemCount: snapshot.data['followingMap'].keys.toList().length,
      itemBuilder: (BuildContext context, int index) {
        return followingItemWidget(id: snapshot.data['followingMap'].keys.toList()[index]);
      }
    );
  },
)
  1. And last I created a widget called 'followingItemWidget' that has a StreamBuilder on a document of a user who I follow. 最后,我创建了一个名为“ followingItemWidget”的小部件,该小部件在我关注的用户的文档上具有StreamBuilder。

This works perfectly, although I believe that there should be a way to do it with only one StreamBuilder. 尽管我相信应该只有一种StreamBuilder可以做到这一点,但它的工作效果非常好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM