【发布时间】:2021-09-21 07:52:17
【问题描述】:
如何将文档的 id 存储在 Flutter Firestore 中的同一个文档中
我的食谱 ID 为空
Future updateRecipeData(RecipeModel recipeModel) async {
await recipeDataCollection.doc().set({
rRecipeTitle: recipeModel.title,
rRecipeBundleName: recipeModel.recipeBundleName,
rCookingTime: recipeModel.cookingTime,
rDateTime: recipeModel.dateTime,
rImgPath: recipeModel.imgPath,
rIngredients: recipeModel.ingredients,
rNumOfLikes: recipeModel.numOfLikes,
rPreparation: recipeModel.preparation,
rServings: recipeModel.servings,
});
print('Data TRANSFORMED');
}
List<RecipeModel> getRecipes(QuerySnapshot snapshot) {
return snapshot.docs.map((doc) {
return RecipeModel(
title: doc.data()[rRecipeTitle],
cookingTime: doc.data()[rCookingTime],
imgPath: doc.data()[rImgPath],
ingredients: List.from(doc.data()[rIngredients]),
preparation: List.from(doc.data()[rPreparation]),
numOfLikes: doc.data()[rNumOfLikes],
dateTime: doc.data()[rDateTime],
servings: doc.data()[rServings],
recipeBundleName: doc.data()[rRecipeBundleName],
recipeId: doc.id,
);
}).toList();
}
Stream<List<RecipeModel>> get recipeData {
return recipeDataCollection.snapshots().map(getRecipes);
}
这是我希望将 doc id 存储在 recipeid 中的代码。
配方型号代码
class RecipeModel {
String title, imgPath, recipeBundleName, recipeId;
String cookingTime, servings;
int numOfLikes;
String dateTime;
List<String> ingredients, preparation;
RecipeModel({
this.title,
this.cookingTime,
this.imgPath,
this.recipeBundleName,
this.servings,
this.numOfLikes,
this.dateTime,
this.ingredients,
this.preparation,
this.recipeId,
});
}
我共享了配方模型,并使用 recipeId 将文档的 id 存储在同一个文档中。
【问题讨论】:
-
"如何将文档的 id 存储在 Flutter Firestore 中的同一个文档中" => 你真的想将文档 ID 作为文档中的字段存储,或者您只是在获取
getRecipes()中的文档 ID 时遇到问题?另外可以分享RecipeModel的代码吗? -
我想将它存储在文档中,或者如果有办法流式传输文档 ID
-
当你做
return snapshot.docs.map((doc) {print(doc.id); return RecipeModel();...时你会得到什么?换句话说,你能检查你在地图中得到了正确的 id 吗? -
我的 id 为空
-
是的,因为您将
QuerySnapshot传递给构建器。但是,如果您当前的代码有问题,StreamBuilder可能会有同样的问题。
标签: firebase flutter dart google-cloud-firestore