在 Flutter 中从 Firebase RealTime DB 接收对象

Receive Objects from Firebase RealTime DB in Flutter

我只想从 firebase 获取对象并将它们转换为 Flutter 中的轮询对象。这是我的投票 class:

class Poll {
  Poll({
    this.id,
    this.name,
    this.description,
    this.questions,
  });

  String id;
  String name;
  String description;
  List<Question> questions;

  factory Poll.fromJson(Map<String, dynamic> json) => Poll(
        name: json['name'],
        description: json['description'],
        questions: List<Question>.from(
            json['questions'].map((x) => Question.fromJson(x))),
      );

  Map<String, dynamic> toJson() => {
        'id': id,
        'name': name,
        'description': description,
        'questions': List<dynamic>.from(questions.map((x) => x.toJson())),
      };
}

这是我的问题Class:

class Question {
  String id;
  String question;
  String customAnswer;
  //Map<String, bool> possibleAnswers;

  //constructor, for Question with one or multiple answer possibilities
  //Question({this.question, this.possibleAnswers});

  // constructor, for a input field (basicly custom answer)
  Question.customAnswer({
    this.id,
    this.question,
    this.customAnswer,
  });

  factory Question.fromJson(Map<dynamic, dynamic> json) =>
      Question.customAnswer(
        question: json['question'],
        customAnswer: json['customAnswer'],
      );

  Map<String, dynamic> toJson() => {
        'id': id,
        'question': question,
        'customAnswer': customAnswer,
      };
}

这是我的实时数据库的截图:

问题是我应该如何在这段代码片段中将 dataSnapshot 投射到我的投票中:

dbRef.once().then((DataSnapshot snapshot) {
      //cast here
});

提前致谢!

经过研究我找到了这个解决方案,它对我的​​情况有效:

void getPolls() {
    dbRef.once().then((DataSnapshot snapshot) {
      polls = _parseData(snapshot);
    });
  }

  List<Poll> _parseData(DataSnapshot dataSnapshot) {
    var companyList = <Poll>[];
    var mapOfMaps = Map<String, dynamic>.from(dataSnapshot.value);

    mapOfMaps.values.forEach((value) {
      companyList.add(Poll.fromJson(Map.from(value)));
    });
    return companyList;
  }