【发布时间】:2022-02-18 21:49:01
【问题描述】:
我正在学习如何在 Flutter 中使用带有 BLoC 模式的“Firestore”。我正在关注 Sagar Suri 的本教程。 https://medium.com/codechai/when-firebase-meets-bloc-pattern-fb5c405597e0。但是,本教程很旧,我正在尝试删除错误并更新它以用于学习目的。我面临2个问题。第一个问题与“updateGoal”功能有关。例如,他从 collection 中复制了目标值,将其转换为 String,然后更新了该值。我在这里遇到错误。任何人都可以帮助我,我如何从用户那里提取目标价值,复制到地图中,投射然后更新。 。这就是我想要做的。
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));
}
类似的问题,我在 removeGoal 函数中遇到。
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});
}
}
有人可以帮助我吗?谢谢。
【问题讨论】:
-
“我在这里遇到错误”请编辑您的问题以显示确切的错误消息以及该错误的堆栈跟踪。
-
@Dharmaraj,是的,我检查了这个,但我正在考虑嵌套属性。例如,目标有 2 个属性构建时间和旅行,我认为教程目标标题的意思是“构建时间”。我从 Firestore 了解这一点,但我正在尝试从教程中学习,这就是为什么我需要以他们的方式做事。
标签: android firebase flutter google-cloud-platform google-cloud-firestore