Reputation: 498
i have a firestore database in which i have "Singer" then inside every singer there is a sub-collection of "Song List" for every singer. i am able to get data from main collection but not from sub-collection. can you guys help?
stream Builder
StreamBuilder(
stream: Firestore.instance.collection('singers').snapshots(),
ListView.Builder
ListView.builder(
itemCount: snapshot.data.documents.length,
itemBuilder: (context, index) => SingleChildScrollView(
this is where i want to show data from sub-collection
Text(
snapshot.data.documents[index]['name'],
style: TextStyle(
fontSize: 20, color: Colors.red[500]),
)
Upvotes: 0
Views: 644
Reputation: 3499
To clarify what you are saying: you want a list of all the songs from all the singers,
Easy-Peasy. CollectionGroup is your friend.
I don't use your environment, but I can see that:
StreamBuilder(
stream: Firestore.instance.collectionGroup('song list').snapshots(),
is the start you need. collectionGroup treats all sub-collections with the name 'song list' as one collection.
NOTE (because this always comes up) Each documentSnapshot returned include a field 'refpath' - which is a string with the entire path to that specific document. You can trivially parse the string to find the parent document(s) or collections(s). For example, a particular song with have in it's refPath ".../singers/{singerID}/songlist/{songID}"
btw, I HIGHLY HIGHLY HIGHLY recommend AGAINST using the singer name as the document ID. Queries are generally of fields, not documentID's, so it won't help your code find the artist, and they are neither unique enough nor randomly distributed enough to be efficient. Let Firestore generate unique documentID's for you, and put the artist name in a field.
Upvotes: 2
Reputation: 769
You can read it like this:
Firestore.instance.collection('singers').snapshot().listen((val)=>{
val.documents.forEach((doc)=>{
doc.reference.collection('song list')
.getDocuments().then((res)=>{
res.douments.forEach((d)=>{
print(d.data);
})
})
})
});
Now this gives you a stream to all docs of collection singers
and thier subcollection
Upvotes: 2
Reputation: 7660
You can get the data from the collection by accessing the subcollection inside the document like this
Firestore.instance.collection('singers').document('aryana sayeed').collection('song list').snapshots()
or
Firestore.instance.collection('singers/aryana sayeed/song list').snapshots()
Upvotes: 2