0

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(() {});
    }
3
  • You have no bound on your inner j loop. It will simply run forever until there is an error. Why don't you instead bound the loop to the number of products you have from the query? Commented Nov 4, 2020 at 18:52
  • I used break statement for that Commented Nov 4, 2020 at 19:01
  • That won't work. The program will crash before the break happens, because you've exceeded the array limit, as the error message is telling you. Commented Nov 4, 2020 at 19:08

1 Answer 1

1

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.
      }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.