Reputation: 45
I have the following database structure:
users
|_____user01
|_____groups
|_____0002
|_____0004
|_____0006
groups
|_____0001
|_____0002
|_____0003
|_____0004
|_____0005
|_____0006
I currently have a StreamBuilder() that creates a list with all the entries it finds in root/groups, so it creates a list of 6 elements.
I need it to create a list using the entries in root/groups as it's doing now, but only those that have an id that matches the IDs of entries present in root/users/user01/groups, so it should create a list with 3 elements (0002, 0004 and 0006).
I can't wrap my head around how to achieve that.
This is my StreamBuild() :
StreamBuilder(
stream: FirebaseFirestore.instance.collection("groups").snapshots(),
builder: (context, snapshots) {
if (snapshots.hasData) {
return ListView.builder(
shrinkWrap: true,
itemCount: snapshots.data.documents.length,
itemBuilder: (context, index) {
DocumentSnapshot documentSnapshot =
snapshots.data.documents[index];
return Dismissable(
child: Card(
)
)
Should I make a firebase query using where() that excludes documents IDs not shared by the two collections and feed the results to the StreamBuilder?
Upvotes: 2
Views: 391
Reputation: 2890
I would recommend you to use a FutureBuilder
for every document
inside the list you are creating using StreamBuilder
and rendering using ListView.builder
.
Create a future that matches each and every document in the list with documents inside the sub-collection of user i.e, groups
.
Future<bool> matchDocs(String id)async{
final result = await FirebaseFirestore.instance.collection('users').doc(FirebaseAuth.instance.currentUser.uid).collection('groups').doc(id).get();
return result.exists;
}
Inside itemBuilder function return a FutureBuilder
.
StreamBuilder(
stream:
FirebaseFirestore.instance.collection("groups").snapshots(),
builder: (context, snapshots) {
if (snapshots.hasData) {
return ListView.builder(
shrinkWrap: true,
itemCount: snapshots.data.documents.length,
itemBuilder: (context, index) {
DocumentSnapshot documentSnapshot =
snapshots.data.documents[index];
return FutureBuilder<bool>(
future: matchDocs(
snapshots.data.documents[index].data()['id'].toString()),
builder: (context, snapshot) {
if (snapshot.hasData) {
if (snapshot.data) {
return Dismissible(key: null, child: null);
}
}
return Container();
}
);
}
);
}
}
)
Note: I did not have any idea about your exact data models, so you should be careful while implementing this solution.
Upvotes: 2