flutterflutter-isar

How to add data to a nested list in Isar?


I have a class that has String and List variables. While the application is running, I need to add values ​​for each model separately to this nested List. This is something like a TODO list, where there are categories of cases, and each category has its own tasks. Tell me, how can I implement adding tasks to Isar?

This is my model:

@collection
class Training {
  Training(this.title, this.weekDay, this.exercises);

  Id id = Isar.autoIncrement;

  String title;

  String weekDay;

  List<Exercise> exercises = [];
}

@embedded
class Exercise {
  Exercise({
    this.title,
    this.sets,
    this.reps,
    this.weight,
    this.time,
    this.description
  });

  String? title;
  int? sets;
  int? reps;
  int? weight;
  String? time;
  String? description;
}

Maybe should make separate collections and link them by reference?


Solution

  • Create your traning class instance first:

    final training = Training("My workout", 'Monday', []);
    

    Fill with data

    training.exercises.add(exercise);
    training.exercises.addAll(exerciseList);
    

    And write to the database

    await isar.writeTxn(() {
      await isar.trainings.put(training); 
    });