Reputation:
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
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
Reputation: 1394
Add 1 more condition
if (snapshot.data == null) {
return const Center(
child: CircularProgressIndicator(),
);
}
Upvotes: 1
Reputation: 162
because stream can be return null value then snapshot.data! as dynamic make error. Please check snapshot.hasData
Upvotes: 1