gilorip
gilorip

Reputation: 45

flutter firestore how I filter data

I have a collection (Groups) inside it fields contain information about users who joined the group,

I want to display to the user all groups he joined.

List groupList = [];

void getAvailableGroups() async {
    await _fireStore
        .collection('Groups')
        .get()
        .then((value) {
        groupList = value.docs;
    });
  }

collection

I tried to convert from map into array but it gives me array within map this is my code

Future createGroup() async{
    GroupRoomModel newGroup = GroupRoomModel(
        groupName: groupName.text,
        groupRoomId: uuid.v1(),
        owner: userModel.uid,
        membersList: controller.membersList,
        membersListUid: controller.membersListUid.cast() // like this
    );
}
...

Also I tried

  Future createGroupFunc() async{
    GroupRoomModel newGroup = GroupRoomModel(
        groupName: groupName.text,
        groupRoomId: uuid.v1(),
        owner: userModel.uid,
        membersList: controller.membersList,
        membersListUid: controller.membersListUid.map((e)=> e).toList()
    );
...

Upvotes: 2

Views: 2891

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 599956

It might be tempting to try filtering based on something like this:

_fireStore
  .collection('Groups')
  .where('membersList', arrayContains: '[email protected]')

This won't work though, as arrayContains only finds something a match when it matches a complete item in the array. You can't use arrayContains to match just a subset of an item.

The common solution is to add an additional array field to your documents with just the property you want to be able to query on. For example:

memberEmails: ['[email protected]', '[email protected]']

With such an addition field, you can query with:

_fireStore
  .collection('Groups')
  .where('memberEmails', arrayContains: '[email protected]')

Upvotes: 9

Related Questions