cipano
cipano

Reputation: 167

Future is returning empty List

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 [];
  }
}

enter image description here

Upvotes: 1

Views: 231

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598817

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();

Upvotes: 2

Related Questions