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.