简体   繁体   中英

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

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));
        });
      });
    });
  }

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM