skip to Main Content

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?

2

Answers


  1. Chosen as BEST ANSWER

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

    Here is code snippet:

    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.


  2. Try this:

    List<Map<String, String>> data = lessons.map((e) => e.toMap()).toList();
    FirebaseFirestore.instance.collection('Courses').add({'key': data});
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search