如何读取 Firebase 数据库扑动的对象的嵌套列表

问题描述 投票:0回答:1

我正在尝试在 flutter 中检索 firebase 实时数据库中的嵌套对象列表 这是数据:




我解释一下: 我有一份课程清单 每节课都有 ID pdf链接 标题 以及 QuestionGroup 的列表 每个问题组都有 法语单词 法语翻译 ... 以及问题列表 每个问题都有 ID 标题 以及答案列表 每个答案都有 ID 标题 这是课程

课程类别:

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']
    );
  }
}

问题小组课:

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,
    
  });

问题类别:

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

答题类别:

class Answer {

  String? id;
  String? title;

  Answer({
    this.id,
    this.title,

  });
}

这是我用来阅读课程的代码:

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.
            });

问题:

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

它无法检索 QuestionGroups 列表,因此它无法转换并且无法工作

flutter firebase firebase-realtime-database nested-lists
1个回答
0
投票

将此行

map['questionGroups']
更改为
map['questionGroups'] ==null? null : List<QuestionGroup>.from(map['questionGroups'].map(x=> x.toJson()))

问题和答案也是如此。

© www.soinside.com 2019 - 2024. All rights reserved.