Home > Enterprise >  Flutter - How to add(create) a nested collection first time and then add fields(update the collectio
Flutter - How to add(create) a nested collection first time and then add fields(update the collectio

Time:11-25

In this method I create a new collection("workouts") the first time a set(exercise set) is saved. A workout will have multiple exercises. So how do I add the next exercises to the same workout?

_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) => {
    
  });
 }
}

CodePudding user response:

In order to add new exercises to existing workouts, you'll need to keep track of the doc or it's ID for your workout. Once you have the workout ID, you will know the path that you can add the new exercise to. 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);
}
  • Related