godopetza
godopetza

Reputation: 107

How to correctly fetch data from firebase using where clauses and custom filters from firebase using flutter

Im trying to fetch data using

Stream<List<User>> getUsers(User user) {
    return _firebaseFirestore
        .collection('users')
        // .where('interestedIn', isEqualTo: _selectInterest(user))
        .snapshots()
        .map((snap) {
      return snap.docs.map((doc) => User.fromSnapshot(doc)).toList();
    });
  }

The filter used in the where clause is as follows

  _selectInterest(User user) {
    if (user.interestPreference == null) {
      return ['HIRING', 'WORK'];
    }
    return user.interestPreference;
  }

In firebase I store interestPreference as an Array with 'HIRING' as the only element in the current user's data, when I try to fetch users with 'HIRING' in their interestedIn which is a string I dont get any data. But when I hardcode the where clause as

.where('interestedIn', isEqualTo: 'HIRING')

I get the data, Can anyone help me solve my dilemma?

Upvotes: 0

Views: 38

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598807

From that last query, it sounds like the interestedIn field in your database is a single string value, like interestedIn: "HIRING".

Your current query returns documents where interestedIn is an array with exactly the two values you specify, so interestedIn: ['HIRING', 'WORK']

If you want to return all documents where interested in is either "HIRING" or "WORK", you can use an IN condition:

.where('interestedIn', whereIn: ['HIRING', 'WORK'])

Or with your helper function:

.where('interestedIn', whereIn: _selectInterest(user))

Upvotes: 1

Related Questions