0
votes

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

1

1 Answers

1
votes

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.
      }
    });