firebase - 将文档添加到 Cloud Firestore 中的集合而不覆盖以前的文档 Flutter
问题描述
在我的颤振应用程序中,我需要将文档添加到集合“influencerPost”中,并且每次用户添加新的“帖子”时,都必须将这个文档添加到之前的文档中……但是此时我只是覆盖了之前的文档。正如您通过我的方法所看到的,我有uploadImage
未来会拾取图像并将其存储到 Firebase 中的存储中。之后我创建了一个名为的集合 influencerPost
,每次新帖子生成新文档时我都必须添加而不覆盖
这是完整的代码:
Future uploadImage(BuildContext context) async {
String fileName = basename(_postImage.path);
Reference firebaseStorageRef =
FirebaseStorage.instance.ref().child('postImage/$fileName');
UploadTask uploadTask = firebaseStorageRef.putFile(_postImage);
TaskSnapshot taskSnapshot = await uploadTask.whenComplete(() => null);
final String downloadUrl = await taskSnapshot.ref.getDownloadURL();
await FirebaseFirestore.instance
.collection('influencerPost')
.doc(firebaseUser.uid)
.set({
"imageUrl": downloadUrl,
'postText': IfUserProfile.post
});
setState(() => CircularProgressIndicator());
}
通过这种方式,我得到了所有文件,但文件被覆盖,而不是我需要保留以前的文件并添加一个新文件。
解决方案
由于您想针对用户维护多个帖子,因此您必须创建子集合。检查下面的代码,我在其中添加了子集合 .collection("post")
Future uploadImage(BuildContext context) async {
String fileName = basename(_postImage.path);
Reference firebaseStorageRef =
FirebaseStorage.instance.ref().child('postImage/$fileName');
UploadTask uploadTask = firebaseStorageRef.putFile(_postImage);
TaskSnapshot taskSnapshot = await uploadTask.whenComplete(() => null);
final String downloadUrl = await taskSnapshot.ref.getDownloadURL();
await FirebaseFirestore.instance
.collection('influencerPost')
.doc(firebaseUser.uid)
.collection("post")
.add({
"imageUrl": downloadUrl,
'postText': IfUserProfile.post
});
setState(() => CircularProgressIndicator());
}
推荐阅读
- python - PHP 和 Python CLI 程序第一次启动太慢(MacOS)
- php - 在更改之前在开发人员模式下查看代码
- python - 使用 RNN 预测名称来源
- javascript - 为什么 Intersection Observer 在第一个元素相交时向所有观察到的元素添加类?
- mongodb - Golang Mongodb bson 字符串切片数组解组错误
- c# - How can I tell if code will run on the client or server with Blazor?
- javascript - How to animate a div scrolling to its last child on page load using JS?
- android - Getting an exact unix time stamp that the user cant change on Android/kotlin
- c++ - How to get length of char array, so that valgrind is satisfied
- r - Using external packages in an RMD as part of an R package