mac
mac

Reputation: 65

How to use Array contains in two different array fields in firebase for flutter

I have a document with two fields, searchkeys1 and searchkeys2, I want my firebase query to check if a value I provided is present in searchkey1 and return, if not search searchkey2, my first attempt was to create a query with the value and first check searchkey1 and if the documents returned are empty, try searchkey2, my problem is I keep getting an error when I am trying to check if any documents were returned

"the getter 'documents' isn't defined for the type 'Stream<QuerySnapshot>'  "

here is my code

startSearch(input) {
        var docSnapshot = FirebaseFirestore.instance
            .collection('items')
            .where('searchkeys1', arrayContains: input.toString()).snapshots();

        if (docSnapshot.documents.length == 0) {

            var docSnapshot2 = FirebaseFirestore.instance
                .collection('items')
                .where('searchkeys2', arrayContains: input.toString()).snapshots();

            return docSnapshot2;




        } else if (docSnapshot.documents.length != 0) {


            return docSnapshot;


        }

Upvotes: 0

Views: 732

Answers (1)

Tarik Huber
Tarik Huber

Reputation: 7418

You need to make your function async and use get insted of smnapshots:

startSearch(input) async {
        var docSnapshot = await FirebaseFirestore.instance
            .collection('items')
            .where('searchkeys1', arrayContains: input.toString()).get();

        if (docSnapshot.documents.length == 0) {

            var docSnapshot2 = await FirebaseFirestore.instance
                .collection('items')
                .where('searchkeys2', arrayContains: input.toString()).get();

            return docSnapshot2;




        } else if (docSnapshot.documents.length != 0) {


            return docSnapshot;


        }

With get you get the data once as you want it. But with snapshots you get a listener for realtime chanegs.

Upvotes: 1

Related Questions