You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter Firestore如何将文档ID存储到同一文档内解决recipeId为空问题

Flutter Firestore将文档ID存储在同文档内的实现方法

你只需要在调用set方法写入数据前,先获取生成的文档ID,再将ID写入对应字段即可,修改updateRecipeData方法如下:

Future updateRecipeData(RecipeModel recipeModel) async {
    // 先创建新文档引用,此时Firestore已生成唯一的文档ID
    final newDocRef = recipeDataCollection.doc();
    await newDocRef.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,
      // 新增字段:把生成的文档ID存入recipeId字段
      'recipeId': newDocRef.id,
      // 若你已定义对应常量rRecipeId,可替换为 rRecipeId: newDocRef.id
    });
    print('Data TRANSFORMED');
}

补充说明

  • 你现有代码中的getRecipes逻辑无需修改,已经正确读取文档ID赋值给RecipeModel的recipeId字段,写入操作添加该字段后,后续查询拿到的recipeId就不会再为null。
  • 如果是更新已有文档的场景,你可以直接把已知的文档ID传入方法,指定文档引用后存入对应字段即可。

内容的提问来源于stack exchange,提问作者Mohammed Nadim

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 09:48:00