Null check operator used on a null value FirebaseFirestore

Viewed 48

I want to sort the posts in my application by date, but when I use orderby I get a null check operator used on a null value error. The problem is that when I type 'where' together with 'orderby' there is a problem.

My code below:

StreamBuilder(
                  stream: FirebaseFirestore.instance
                      .collection('posts')
                      .where('uid', isEqualTo: widget.uid)
                      .orderBy(
                        'datePublished',
                        descending: true,
                      )
                      
                      .snapshots(),
                      
                  builder: (context, snapshot) {
                    if (snapshot.connectionState == ConnectionState.waiting) {
                      return const Center(
                        child: CircularProgressIndicator(),
                      );
                    }
                    return ListView.builder(
                        primary: false,
                        shrinkWrap: true,
                        itemCount: (snapshot.data! as dynamic).docs.length,
                        itemBuilder: (context, index) {
                          DocumentSnapshot snap =
                              (snapshot.data! as dynamic).docs[index];
3 Answers

Firestore is an optimized database. As a result, you have to create composite indexes for complex queries, like the one you are doing (combining orderBy with where), to work.

To solve this problem, look at the logs where you are running Flutter. you should see a Firebase Console link that will take you straight to creating the query. Create the query, wait for 5 minutes or less for it to build, then try the code again. It should work.

Add 1 more condition

if (snapshot.data == null) {
                      return const Center(
                        child: CircularProgressIndicator(),
                      );
                    }

because stream can be return null value then snapshot.data! as dynamic make error. Please check snapshot.hasData

Related