Rohan Choudhary
Rohan Choudhary

Reputation: 303

Flutter Range Error Firestore array inside collection

I am fetching data from a product array of documents of collection orders.

QuerySnapshot querySnapshot = FirebaseFirestore.instance.collection("orders").get();
var x = querySnapshot.docs[i].data()["products"][j]["oprice"];

where i & j are iterators.

But the program crashes after range value goes out of bound. Now how to check if x exists for these indexes.

if (x == null) 
          break;
        

This fails by giving error

[ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: RangeError (index): Invalid value: Not in inclusive range 0..1: 2

Full code:

QuerySnapshot querySnapshot =
        await FirebaseFirestore.instance.collection("orders").get();

    for (int i = 0; i < querySnapshot.docs.length; i++) {
      var a = querySnapshot.docs[i];

      for (int j = 0;; j++) {
        if (a.data()["products"][j]["oprice"] == null) break;
   
        orderList.add(OrderList(
            orderNumber: a.data()["products"][j]["orderid"],
            price: a.data()["products"][j]["oprice"],
            addressReciever: a.data()["products"][j]["caddress"],
            mobileNumber: 9999123490.toString(),
            paymentStatus:
                a.data()["products"][j]["paymode"].toString().toUpperCase() ==
                        "CASH ON DELIVERY"
                    ? "Cash on Delivery"
                    : "Paid",
            recieverName: a.data()["products"][j]["cname"],
            orderStatus: a.data()["products"][j]["status"],
            productName: a.data()["products"][j]["name"]));
      }
      setState(() {});
    }

Upvotes: 0

Views: 62

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317467

You need to bound your inner j loop by the size of the products array.

      for (int j = 0; a.data()["products"].length; j++) {
          // a.data()["products"][j] is safe to use here.
      }

Upvotes: 1

Related Questions