简体   繁体   中英

Flutter Firestore StreamBuilder on list of references

The Firestore database is build of one collection of users. Every user document has some public data and a array of users ID's that he follows called following. In the Flutter app I would like to create a StreamBuilder on the following array. 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.

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').
  2. Used a StreamBuilder on that document:
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.

This works perfectly, although I believe that there should be a way to do it with only one StreamBuilder.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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