Home > Blockchain >  Flutter model for FireBase - add a List of objects
Flutter model for FireBase - add a List of objects

Time:09-04

I try to create a collection of courses that contains a sub-collection of lessons, when I add a single lesson, it works, but I don't know how to add a list of object lessons !??

class Lesson{
  String LessonName;
  int LessonChapter;
  
  Lesson({required this.LessonName,required this.LessonChapter});

  Map<String, Object?> toMap() {
    return {
      'LessonName': LessonName,
      'LessonChapter': LessonChapter,  
    };
  }
}

class Course{
  String CourseName;
  List<Lesson> Lessons;

  Course({required this.CourseName, required this.Lesson});

  Map<String, dynamic> toMap() {
    return {
      'CourseName': CourseName,
      'Lessons': Lessons.first.toMap(),  <---- here
    };
  }
}
List<Lesson> Lessons=[{'Lesson1','3'},{'Lesson2','4'}] ;

FirebaseFirestore.instance.collection('Courses')
   .add(Course(
            CourseName: CourseName,
            Lessons: Lessons   <---- here
        ).toMap()
);

Can you please help me?

CodePudding user response:

Try this:

List<Map<String, String>> data = lessons.map((e) => e.toMap()).toList();
FirebaseFirestore.instance.collection('Courses').add({'key': data});

CodePudding user response:

finally, I was able to solve this by editing this section:

Map<String, dynamic> toMap() {
List lessonsMap = [] ;
lessons.forEach((element) {lessonsMap.add(element.toMap()) ;});

return {
  'CourseName': CourseName,
  'lessons': lessonsMap
};

}

if you have a better solution, please share it.

  • Related