【问题标题】:Flutter - How to add(create) a nested collection first time and then add fields(update the collection) next time in FirestoreFlutter - 如何第一次添加(创建)嵌套集合,然后下次在 Firestore 中添加字段(更新集合)
【发布时间】:2021-11-23 16:20:48
【问题描述】:

在这种方法中,我在第一次保存一组(锻炼组)时创建一个新的集合(“锻炼”)。一次锻炼将有多个锻炼。那么如何将下一个练习添加到同一锻炼中?

_saveExerciseSetForUser() {
if (currentUser != null) {
  FirebaseFirestore.instance
      .collection('users')
      .doc(currentUser!.uid)
      .collection("workouts")
      .doc()
      .collection("exercises")
      .doc(exerciseId)
      .collection("sets")
      .doc()
      .set({
    
    "setNo.": setCount,
    "weight": weightController.text,
    "reps": repsController.text,
    "toFailure": false
  }).then((value) => {
    
  });
 }
}

【问题讨论】:

    标签: firebase flutter dart google-cloud-firestore


    【解决方案1】:

    为了在现有锻炼中添加新锻炼,您需要跟踪文档或锻炼 ID。获得锻炼 ID 后,您将知道可以将新锻炼添加到的路径。 users/$userId/workouts/$workoutId/exercises/$exerciseId/sets

    Future<void> _saveExerciseSetForUser([String? workoutId]) async {
      if (currentUser == null) {
        return;
      }
    
      final data = {
        "setNo.": setCount,
        "weight": weightController.text,
        "reps": repsController.text,
        "toFailure": false,
      };
    
      final workoutDoc = FirebaseFirestore.instance
        .collection('users')
        .doc(currentUser!.uid)
        .collection("workouts")
        // if workoutId is null, this will create a new workout
        .doc(workoutId);
    
      // save doc id somewhere
      final workoutDocId = workoutDoc.id;
    
      await workoutDoc.collection("exercises")
        .doc(exerciseId)
        .collection("sets")
        .doc()
        .set(data);
    }
    

    【讨论】:

    • “// 将文档 ID 保存在某处”是什么意思?还有,为什么要作为参数传递锻炼ID,还没生成的时候从哪里来?!
    • 如果您要为该锻炼保存更多练习,则需要跟踪 id。因此,您需要将其保存(缓存)到设备中,以便再次引用它
    • 缓存它在哪里,保存的首选项?
    • hive,保存的首选项,颤振缓存管理器。他们都工作?
    • 最后一件事,我这里设置数据,也就是第一组。要添加连续组,我必须更新练习文档?
    猜你喜欢
    • 1970-01-01
    • 2016-11-16
    • 1970-01-01
    • 2023-03-24
    • 2022-01-24
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    • 1970-01-01
    相关资源
    最近更新 更多