简体   繁体   中英

How to remove a nested property from Firestore collection

I am learning how to use "Firestore" with BLoC pattern in Flutter. I am following this tutorial by Sagar Suri. https://medium.com/codechai/when-firebase-meets-bloc-pattern-fb5c405597e0 . However, this tutorial is old and I am trying to remove bugs and update it for learning purpose. I am facing 2 issue in it. First issue is related with 'updateGoal' function. In example, he copied goals value from collection, cast it into the String and then updated the value. I am getting an error here. Anybody can help me, how I can extract goals value from users, copy into Map, cast it and then update. 在此处输入图像描述 . This is what I am trying to do.

Future<void> uploadGoal(String title, String documentId, String goal) async {
    DocumentSnapshot doc =
    await _firestore.collection("users").doc(documentId).get();
    Map<String, String> data = doc.data()! as Map<String, String>;
    /****/
    //Getting error here "The operator '[]' isn't defined for the type 'Object? Function()'."
    Map<String, String> goals = doc.data["goals"] != null
         ? doc.data["goals"].cast<String, String>()
         : null;
    /****/
    if (data != null) {
      data[title] = goal;
    } else {
      data = Map();
      data[title] = goal;
    }
    return _firestore
        .collection("users")
        .doc(documentId)
        .set({'goals': data, 'goalAdded': true},  SetOptions(merge: true));
  }

Similar issue, I am facing in removeGoal function.

void removeGoal(String title, String documentId) async {
    DocumentSnapshot doc =
    await _firestore.collection("users").doc(documentId).get();
    Map<String, String> data = doc.data()! as Map<String, String>;
    //How to remove goals title from collection here
    goals.remove(title);
    if (goals.isNotEmpty) {
      _firestore
          .collection("users")
          .doc(documentId)
          .update({"goals": goals});
    } else {
      _firestore
          .collection("users")
          .doc(documentId)
          .update({'goals': FieldValue.delete(), 'goalAdded': false});
    }
  }

Anybody can help me? Thanks.

This looks wrong:

Map<String, String> data = doc.data()! as Map<String, String>;

While all the keys in your document are strings, the goals value is an object/dictionary instead of a string. So at best you can cast it to:

Map<String, dynamic> data = doc.data()! as Map<String, dynamic>;

Once you do that, the statement you commented out to get the goals field should work, but it it doesn't: provide an updated in to your question with the updated code, and the exact error message and stack trace you 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