Home > OS >  Firestore query in Flutter
Firestore query in Flutter

Time:10-31

I wanted to improve my Firestore query, but I got an error. I have simple Firestore db: collection 'Spanish' where each collection has only one document 'words'. The original working code code is:

var myData = await FirebaseFirestore.instance
      .collection('Spanish')
      .get()
      .then((snapshot) {
    if (snapshot != null) {
      snapshot.docs.forEach((element) {
        element.data().forEach((key, value) {
          myMap.putIfAbsent(key, () => value);
          myDictionary.add(key   '@'   value);
        });
      });

Since the collection has only one document I tried to improve the query by getting all fields from the selected document, so my new query is:

var myData = await FirebaseFirestore.instance
      .collection('Spanish').doc('words')
      .get()
      .then((snapshot) {
    if (snapshot != null) {
      snapshot.data().forEach((key, value) {
          myMap.putIfAbsent(key, () => value);
          myDictionary.add(key   '@'   value);
        }); 

Now I am getting error on forEach, which says:

"The method 'forEach' can't be unconditionally invoked because the receiver can be 'null'.

Try making the call conditional (using '?.') or adding a null check to the target"

But I am checking for null in "if (snapshot != null)" Any ideas why?

CodePudding user response:

That is because data() could return null. Add a null-check operator or a bang operator there.

snapshot.data()?.forEach(...);

CodePudding user response:

from the official documentation of the firebase firestore

A DocumentSnapshot is returned from a query, or by accessing the document directly. Even if no document exists in the database, a snapshot will always be returned.

so actually using if (snapshot != null) doesn't do anything since it will never be null

when you call the data() on the snapshot, you got a Map<String, dynamic> and what exactly could be null, since it will be coming from a firebase request, dart doesn't know if it's null or not, so you need to take a null safety action over it.

since you said that the collection has that words for sure, then you could tell dart this with ! :

snapshot!.data()!

or if you're not sure that is null or not use a ?, then handle it with a if else :

if(snapshot?.data()? == null) {
  /* action */
  }  else {
  /* action */  
  }
  • Related