I try to get data from firebase and give me this error _CastError (Null check operator used on a null value)


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(!).

getdata() async {
    await FirebaseFirestore.instance 
        .then((value) {
      setState(() {
        List.from(value.data()!['totkm']).forEach((element) {


The problem is:

await FirebaseFirestore.instance 

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()....

Answered By – Frank van Puffelen

Answer Checked By – Jay B. (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *