user19802992
user19802992

Reputation:

Null check operator used on a null value FirebaseFirestore

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];

Upvotes: 2

Views: 135

Answers (3)

Obum
Obum

Reputation: 1623

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.

Upvotes: 2

Harsh Sureja
Harsh Sureja

Reputation: 1394

Add 1 more condition

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

Upvotes: 1

ThanhNguyen
ThanhNguyen

Reputation: 162

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

Upvotes: 1

Related Questions