How to read nested lists of objects firebase database flutter

50 Views Asked by At

i am trying to retrieve a list of nested objects in firebase realtime database in flutter here is the data: enter image description here


enter image description here


enter image description here


let me explain: i have a list of Lessons every lesson has id pdfLink title and a list of QuestionGroup every questionGroup has frenchWord frenchTranslation ... and a List of Questions every question has id title and a list of answers every answer has id title here is the classes

Lesson Class:

class Lesson {

  String? id;
  String? pdfLink;
  List<QuestionGroup>? questionGroups;
  List<Question>? questions;
  String? title;
  String? videoLink;
  String? yearId;
  
  

  Lesson({
    this.id,
    this.pdfLink,
    this.questionGroups,
    this.questions,
    this.title,
    this.videoLink,
    this.yearId,
    
  });
factory Lesson.fromMap(Map<dynamic, dynamic> map) {
    return Lesson(
      id: map['id'] ,
      yearId: map['yearId'] ,
      title: map['title'] ,
      pdfLink: map['pdfLink'],
      videoLink: map['videoLink'],
      questionGroups: map['questionGroups'],
      questions: map['questions']
    );
  }
}

QuestionGroup Class:

class QuestionGroup {

  String? id;
  String? frenchWord;
  String? arabicWord;
  String? frenchTranslation;
  String? arabicTranslation;
  
  
  List<Question>? questions;

  QuestionGroup({
    this.id,
    this.frenchWord,
    this.arabicWord,
    this.frenchTranslation,
    this.arabicTranslation,
    this.questions,
    
  });

Question Class:

class Question {
  String? id;
  String? title;  
  String? rightAnswer;
  List<Answer>? answers;
  Question({
    this.id,
    this.title,
    this.answers,
    this.rightAnswer,
    
  });
}

Answer Class:

class Answer {

  String? id;
  String? title;

  Answer({
    this.id,
    this.title,

  });
}

Here the code i use to read the lessons:

await Firebase.initializeApp();
       DatabaseReference yearsRef = FirebaseDatabase.instance.ref('lessons');
          yearsRef.onValue.listen((event) {
            for (final child in event.snapshot.children) {
              log('message');
              final lesson = child as Lesson;
              lessons!.add(lesson);
              log(lesson.toString());
              }
            }, onError: (error) {
              // Error.
            });

the problem : Unhandled Exception: type 'List<Object?>' is not a subtype of type 'List<QuestionGroup>?'

it cannot retrieve the QuestionGroups list so it is not casting and not working

1

There are 1 best solutions below

3
S. M. JAHANGIR On

Change this line map['questionGroups'] to map['questionGroups'] ==null? null : List<QuestionGroup>.from(map['questionGroups'].map(x=> QuestionGroup.fromMap(x)))

Same goes for Question and Answer.