I am trying to get a stream of a single document that has multiple collections from Firebase Firestore.
data structure:
{
"answers": [
{
"test@email.com": {
"anger": [
{
"1": {
"answerText": [
"answer1",
"answer2",
"answer3"
],
"category": "anger",
"dateCreated": "2023-05-05T14:54:49.297",
"lastModified": "2023-06-05T14:54:49.297",
"step": "1",
"watchedVideo": false
}
},
{
"2": {
"answerText": [
"answer1",
"answer2",
"answer3"
],
"category": "anger",
"dateCreated": "2023-05-05T14:54:49.297",
"lastModified": "2023-06-05T14:54:49.297",
"step": "2",
"watchedVideo": false
}
}
],
"anxiety": [
{
"1": {
"answerText": [
"answer1",
"answer2",
"answer3"
],
"category": "anxiety",
"dateCreated": "2023-05-05T14:54:49.297",
"lastModified": "2023-06-05T14:54:49.297",
"step": "1",
"watchedVideo": false
}
},
{
"3": {
"answerText": [
"answer1",
"answer2",
"answer3"
],
"category": "anxiety",
"dateCreated": "2023-05-05T14:54:49.297",
"lastModified": "2023-06-05T14:54:49.297",
"step": "3",
"watchedVideo": false
}
}
]
}
}
]
}
Below is what I currently have working but this is only getting one of the collections for the user.
I want all of the collections below the user's email address.
Stream<Iterable<AnswerModel>> getAllUserAnswers({
required UserModel user,
}) {
String uid = user.email;
print('GETTING USER ANSWERS: answers/$uid/');
return FirebaseFirestore.instance
.collection('answers').doc(uid).collection('anger')
.snapshots()
.map(
(snapshot) => snapshot.docs
.map((doc) => AnswerModel.fromMap(doc.data())).toList()
);
}
And here is how I am using the method above inside a StreamBuilder.
return StreamBuilder(
stream: answerRepo.getAllUserAnswers(user: userModel),
builder: (context, snapshot) {
if (snapshot.hasData) {
userAnswers = snapshot.data as List<AnswerModel>;
if (userAnswers.isNotEmpty) {
return ListView.builder(
padding: const EdgeInsets.fromLTRB(20, 20, 20, 20),
itemCount: userAnswers.length,
itemBuilder: (context, index) {
var category = userAnswers[1].category;
return Padding(
padding: const EdgeInsets.fromLTRB(0, 20, 0, 20),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// ...add items to display info from stream
],)
);
},
),
}
}
});