Rohan Choudhary
Rohan Choudhary

Reputation: 303

Flutter firebase query snapshot error: "Unhandled Exception: Bad state: No element"

Fetching document with required field value, but this doesn't work

await FirebaseFirestore.instance
            .collection('orders')
            .where("id", isEqualTo: orderList[index].id)
            .get()
            .then((snapshot) {
          snapshot.docs.first.reference.update({"status": 'Rejected'});
          print("yes");
        });

But this works

await FirebaseFirestore.instance
        .collection('orders')
        .where("id", isEqualTo: orderList[index].id)
        .get()
        .then((snapshot) {
      //snapshot.docs.first.reference.update({"status": 'Rejected'});
      print("yes");
    });

Error

E/flutter (10845): [ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: Bad state: No element

Upvotes: 1

Views: 895

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317372

The QuerySnapshot object returned by a query can return 0 or more DocumentSnapshot objects. You should check to see if there are more then 0 before indexing into the docs array.

await FirebaseFirestore.instance
    .collection('orders')
    .where("id", isEqualTo: orderList[index].id)
    .get()
    .then((snapshot) {
      if (snapshot.docs.length > 0) {
        snapshot.docs.first.reference.update({"status": 'Rejected'});
      }
      else {
        // Figure out what you want to do if the list is empty.
        // This means your query matched no documents.
      }
    });

Upvotes: 2

Related Questions