Firestore 数据库是由一个用户集合构建的。每个用户文档都有一些公共数据和他遵循的用户 ID 数组,称为以下内容。在 Flutter 应用程序中,我想在以下数组上创建一个 StreamBuilder。因此,当用户将某人添加到他的关注数组时 - 它将被添加到流中,并且当以下列表中的用户更改其数据时 - 流也会更新。
我想也许使用引用列表('users/usersid3'
)而不是ID列表('userid3'
),但我不知道如何实现它。
这就是数据库的结构。
users
- user1id
- some public data
- following: [user2id, user3id]
- user2id
- some public data
- following: []
- user3id
- some public data
- following: [user2id]
因此,有一个解决方法可以解决此问题。
- 我将以下列表保存为地图(名为"followMap")在单独的文档"followDoc"中。
- 在该文档上使用了流生成器:
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]);
}
);
},
)
- 最后,我创建了一个名为"followItemWidget"的小部件,它在我关注的用户的文档上有一个流构建器。
这非常有效,尽管我相信应该有一种方法可以只用一个 StreamBuilder 来做到这一点。