Why does flutter streambuilder query using 'orderby' cause an error

Viewed 184

Why does my StreamBuilder return something went wrong? This stream works perfectly fine but when add orderBy it says that something went wrong. Database

Padding(
                      padding: const EdgeInsets.only(
                        left: 20,
                      ),
                      child: StreamBuilder<QuerySnapshot>(
                        stream: FirebaseFirestore.instance
                            .collection("notifications")
                            .where("parentUID",
                                isEqualTo:
                                    FirebaseAuth.instance.currentUser!.uid)
                            .orderBy('timestamp')
                            .snapshots(),
                        builder: (BuildContext context,
                            AsyncSnapshot<QuerySnapshot> snapshot) {
                          if (snapshot.hasError) {
                            return Text('Something went wrong');
                          }

                          if (snapshot.connectionState ==
                              ConnectionState.waiting) {
                            return Text("Loading");
                          }
                          return Column(
                            children: snapshot.data!.docs.map(
                              (DocumentSnapshot document) {
                                Map<String, dynamic> data =
                                    document.data()! as Map<String, dynamic>;
                                return adminNotifCard(
                                  text1: data['notifTitle'],
                                  text2: data['notifNotes'],
                                );
                              },
                            ).toList(),
                          );
                        },
                      ),
                    ),

Error

2 Answers

I solved the issue by going to the index tab in cloud firestore
enter image description here

enter image description here

And chose the notification collection and made it ascending, it didnt work at first, but after saying building, it said enabled and I hot restart. It worked

  1. Goto index Tab From firebase firestore.
  2. Add index
Related