Home > Software design >  how to query a Firestore DocumentReference field in Flutter
how to query a Firestore DocumentReference field in Flutter

Time:11-23

I have Item collection it contains a reference named category

as you can see

enter image description here

I wanna search if category is equal to category reference it should show me all data with that category reference

here I am searching for the category

 finalReference({String? reference}) {
    String reference ='categories/${widget.firstDocs}/FirstCategories/$secondKey/SecondCategories/${snapData[index].id}'
    return FirebaseFirestore.instance
        .collection('items').where('category',isEqualTo: reference)
        .snapshots();
  }

but showing nothing

and when removing where method is shows me all kind of categories references

and printing category like this:

DocumentReference<Map<String, dynamic>>(categories/7gGcmhHZBu7UbnrpPAov/FirstCategories/TyFolH2B1j0b8AUz55ZA/SecondCategories/vIeGUNBHZcNudEwMirQY)

here I am showing data

 StreamBuilder<QuerySnapshot<Map<String, dynamic>>>(
        stream: CallData().finalReference(reference: widget.finalReference),
        builder: (context, snapshot) {
          if (snapshot.hasError) {
            return Center(child: Text('snapshot Error:${snapshot.error}'));
          }
          if (snapshot.hasData) {
            var snapData = snapshot.data!.docs;
            if (kDebugMode) {
              print(snapData.length);
            }
            return ListView.builder(
                itemCount: snapData.length,
                itemBuilder: (context, index) {

                  if (kDebugMode) {
                    print('items is ${snapData[index].get('title')}');
                    print('items is ${snapData[index].get('category')}');
                  }
                  return Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      CategoryCard(
                        hasIcon: false,
                        mTitle: '${snapData[index].get('title')}',
                        mSubTitle: '${snapData[index].get('category')}',
                      ),
                      const Divider(),
                    ],
                  );
                });
          }

          return const Center(child: CircularProgressIndicator());
        },
      ),

CodePudding user response:

You're passing a string value to the query, while you store a DocumentReference. Since the types are different, the values are never equal and you get no result.

To make it work, pass an actual DocumentReference to the query:

finalReference({String? reference}) {
  String reference ='categories/${widget.firstDocs}/FirstCategories/$secondKey/SecondCategories/${snapData[index].id}'
  return FirebaseFirestore.instance
    .collection('items').where('category',isEqualTo: FirebaseFirestore.instance.doc(reference))
    .snapshots();
 }
  • Related