Solution 1 :
This part of your code does not match your data structure:
final rooms = await FirebaseFirestore.instance
.collection('rooms')
.where('users', arrayContains: uid)
.get();
Your users
is a Map
and not an array, so arrayContains
won’t work here. As said in my answer to your previous question, you have to use dot notation to test nested fields:
final rooms = await FirebaseFirestore.instance
.collection('rooms')
.where('users.uid1', isEqualTo: uid)
.where('users.uid2', isEqualTo: otherValue)
.get();
That is closest to what you tried in your previous question: Firestore conditional array query. It performs an AND condition on the uid1
and uid2
subfields of users
.
If instead you want to get all rooms that the user is a participant in, you need an (additional) field that is an array with the UIDs of all participants.
participantUIDs: ["uid1", "uid2"]
Then you can do:
final rooms = await FirebaseFirestore.instance
.collection('rooms')
.where('participants', arrayContains: uid)
.get();
Problem :
My below code is returning an empty list, even though it SHOULD return data corresponding to my data stored in my firestore database. Also to note: The otherUserId print statement is not getting printed. How can I fix this issue?
Future<List<String>> getChattingWith(String uid) async {
List<String> chattingWith = [];
try {
// create list of all users user is chatting with
final rooms = await FirebaseFirestore.instance
.collection('rooms')
.where('users', arrayContains: uid)
.get();
for (final room in rooms.docs) {
final users = room['users'] as Map<String, dynamic>;
final otherUserId = users['uid1'] == uid ? users['uid2'] : users['uid1'];
print("otherUserId999: $otherUserId");
chattingWith.add(otherUserId);
}
print("chattingWith: $chattingWith");
return chattingWith;
} catch (error) {
print("error: $error");
return [];
}
}
Comments
Comment posted by Ozan Taskiran
So it jumps in the catch block? What is the error?
Comment posted by cipano
No, it just prints “chattingWithList: []”
Comment posted by Ozan Taskiran
So your room.docs is empty, can you check it?
Comment posted by cipano
No, it is not empty. I am trying to fetch all rooms where the users array contains the uid. After that I create a list of the user ids which are not equal to the uid. So basically I want to create a list of all uids which a user is chatting with. But the data is fine, just the query is not working.
Comment posted by cipano
I have added an image of the users array. Maybe my query is wrong?
Comment posted by cipano
The GOAT himself. Thank you a lot for your time and help! Learned a lot today thanks to you!