I try to fetch data from array field, but I give the error. The error is:
_CastError (Null check operator used on a null value)
I don't know where is the problem in this code.
when I deleted null check operator(!) in this line List.from(value.data()!['totkm']).forEach((element), VSCode also give me error and The VSCode asks me to put a null check operator(!).
List<int>totkm=[];
getdata() async {
await FirebaseFirestore.instance
.collection("TotalKM")
.doc()
.get()
.then((value) {
setState(() {
List.from(value.data()!['totkm']).forEach((element) {
totkm.add(int.parse(element));
});
});
});
}
CodePudding user response:
The problem is:
await FirebaseFirestore.instance
.collection("TotalKM")
.doc()
Calling doc() without arguments generates a reference to a new, non-existing document. You then call get() on that reference, which gives you a snapshot for that non-existing document, so without any data. Then calling value.data()! is an error, as by using ! you tell the compiler that you know the data() cannot be null, and that is false.
To get rid of the error most easily, use ? instead of !.
But more likely, you'll need to pass the document ID of the document you want to load into the call to doc(): ...doc("idOfDocumentYouWantToLoad").get()....
