0

this is my users collection in cloud fire store:

users collection

this is the function that gets users from users collection in firestore

 Stream<QuerySnapshot> fetchUsersInSearch() {
    return Firestore.instance.collection('users').snapshots();
  }

i use this method

  final emailResults = snapshot.data.documents
              .where((u) => u['email'].contains(query));

in the following streamBuilder to fetch users by their email.

i have this streamBuilder to populate the data on screen

return StreamBuilder<QuerySnapshot>(
        stream: DatabaseService().fetchUsersInSearch(),
        builder: (context, AsyncSnapshot<QuerySnapshot> snapshot) {

          final emailResults = snapshot.data.documents
              .where((u) => u['email'].contains(query));

          if (!snapshot.hasData) {
            return Container(
              color: Theme.of(context).primaryColor,
              child: Center(
                child: Text(
                  '',
                  style: TextStyle(
                      fontSize: 16, color: Theme.of(context).primaryColor),
                ),
              ),
            );
          }
          if (emailResults.length > 0) {
            return Container(
              color: Theme.of(context).primaryColor,
              child: ListView(
                children: emailResults
                    .map<Widget>((u) => GestureDetector(
                          child: Padding(
                            padding: const EdgeInsets.all(0.1),
                            child: Container(
                              padding: EdgeInsets.symmetric(vertical: 5),
                              decoration: BoxDecoration(
                                  color: Theme.of(context).primaryColor,
                                  border: Border(
                                      bottom: BorderSide(
                                          width: 0.3, color: Colors.grey[50]))),
                              child: ListTile(
                                leading: CircleAvatar(
                                        backgroundColor:
                                            Theme.of(context).primaryColor,
                                        backgroundImage:
                                            NetworkImage(u['userAvatarUrl']),
                                        radius: 20,
                                      ),
                                title: Container(
                                  padding: EdgeInsets.only(left: 10),
                                  child: Column(
                                    crossAxisAlignment:
                                        CrossAxisAlignment.start,
                                    children: [
                                      Text(u['email'],
                                          style: TextStyle(
                                              fontSize: 16,
                                              color: Theme.of(context)
                                                  .accentColor),
                                          overflow: TextOverflow.ellipsis),
                                      SizedBox(
                                        height: 5,
                                      ),
                                
                                    ],
                                  ),
                                ),
                                
                              ),
                            ),
                          ),
                          onTap: () {
                            showUserProfile(u['id']);
                          },
                        ))
                    .toList(),
              ),
            );
          } else {
            return Container(
              color: Theme.of(context).primaryColor,
              child: Center(
                child: Text(
                  'No results found',
                  style: TextStyle(
                    fontSize: 16,
                    color: Theme.of(context).accentColor,
                  ),
                ),
              ),
            );
          }
        });

this is working perfectly and fetching users inside a listView by their email...

p.s: the (query) is a string i type in a seach bar.

how can i make a query to fetch users by their otherUsernames...the second field in the screenshot of the users collection ?!

i tried this:

  final otherUsernamesResults = snapshot.data.documents
              .where((u) => u['otherUsernames'].contains(query));

but its returning this error:

The method 'contains' was called on null.
Receiver: null
Tried calling: contains("#username1")

what am i doing wrong here ?!!

any help would be much appreciated..

1 Answer 1

1

Try this:-

Stream<QuerySnapshot> getUsers() {
  final usersCollection = FirebaseFirestore.instance.collection('users');
  return usersCollection.where('otherUsernames', arrayContainsAny: ['username1', 'username2']);
}

For firestore version 0.16.0

Sign up to request clarification or add additional context in comments.

1 Comment

i made some corrections to your answer to make it work: Stream<QuerySnapshot> getUsers() { final usersCollection = Firestore.instance.collection('users').snapshots(); return usersCollection.where('otherUsernames', arrayContainsAny: ['username1', 'username2']); } but at least the the approach made me happy that we can search for users by sub collections

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.