Home > Net >  How do I filter CollectionGroup Query with 'where' in Flutter Firestore
How do I filter CollectionGroup Query with 'where' in Flutter Firestore

Time:10-13

I Have a CollectionGroup query which displays all document data from 'school_news' collection in a Listtile with Streambuilder and ListView.

But now I want to only show the document data in a ListView/Listtile where 'name' field equals name in a list , like :

List userSelections = ['Liebenberg', 'St Michaels' , 'School C' ];


FirebaseFirestore.instance
    .collectionGroup('school_news')
    .where('name', arrayContainsAny: userSelections )
    .snapshots(),

So what I want now is to only then display the document data fields in a ListView/Listtile where the 'name' fields are Liebenberg, St Michaels and 'School C' instead of all the document data in 'school_news' collection .

Is something like that possible ? I tried with the code above but with no luck, So I am not sure what I'm missing .

Any help or guidance would be greatly appreciated .Thank you

UPDATE

I have updated as per answer and included full code , as below :

class UserHome extends StatefulWidget {
  const UserHome({Key? key}) : super(key: key);

  @override
  _UserHomeState createState() => _UserHomeState();
}

class _UserHomeState extends State<UserHome> {
  final uid = FirebaseAuth.instance.currentUser!.uid;
  final db = FirebaseFirestore.instance;

  List userSelections = ['Liebenberg', 'St Michaels'];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: StreamBuilder<QuerySnapshot>(
        stream: FirebaseFirestore.instance
            .collectionGroup('school_news')
            .where('name', whereIn: userSelections)
            .snapshots(),
        builder: (context, snapshot) {
          if (!snapshot.hasData) {
            return Center(
              child: Text('Loading '),
            );
          } else
            return ListView(
              children: snapshot.data!.docs.map((doc) {
                return Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: GestureDetector(
                    onTap: () {},
                    child: Column(
                      children: [
                        ListTile(
                          leading: Text(doc['title']),
                        ),
                        SizedBox(
                          height: 10,
                        ),
                      ],
                    ),
                  ),
                );
              }).toList(),
            );
        },
      ),
    );
  }
}

Firestore BD / Collection Path

Seems like no data is returned as the page just displays 'Loading' . The link for creating the new index for the 'WhereIn' I also dont get .

Anything I am doin wrong ?

Thanks for the help so far .

CodePudding user response:

You should use whereIn instead of arrayContainsAny. replace this line

.where('name', arrayContainsAny: userSelections )

with this one:

.where('name', whereIn: userSelections)

Remember that Firestore has a built-in constraint where you can't have more than 10 items in your list. It means your list userSelections cannot have more than 10 values (otherwise you may want to do the filter client side, depending on your use case)

Also, in your 1st execution, you may need to add a new index... just follow the web link (in the new error message) that will help create this required index directly in Firestore.

  • Related