I am calling the following method to retrieve an item status from Firestore. There will be scenarios where the method is being called before any other method which ideally will update the collection with the required column, in this case called is_item_ordered. This throws the error: Unhandled Exception: NoSuchMethodError: The method '[]' was called on null. Tried calling: [] ("is_ordered"). The is_ordered is the field data which would be null unless another method which updates the collection is already called. It is not always in this sequence. How to I chec that the collection has no field and return a false/null etc?
Future<bool> getItemOrderedStatus(String itemId, String buyerId) async {
var document = FirebaseFirestore.instance
.collection(ordered_items)
.doc(buyerId)
.collection(order_collection)
.doc(itemId);
return document.get().then((value) => value.data()["is_ordered"]);
}
I have tried:
return document.get().then((value) => value.data()["is_ordered"])??false; //but the error still
//occurs.
The calling method which throws the error is below:
Future<bool> isOffered() async {
//I need to check for a null before doing a return;
return isOnOffer = await Ordering()
.getItemOrderedStatus(widget.itemId, widget.currentUserId);
}
Trying to check for null as below still fails with same error:
Future<bool> isOffered() async {
//I need to check for a null before doing a return;
return isOnOffer = await Ordering()
.getItemOrderedStatus(widget.itemId, widget.currentUserId)??false;
}
This is a common error whenever I access collections whose field does not exist. I have googled yet no clear answer how to check for non existing fields.