Получение объектов из базы данных Firebase RealTime во Flutter

Я просто хочу получить объекты из firebase и передать их объекту опроса во Flutter. Это мой класс опроса:

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

Заранее спасибо!

Интеграция Angular - Firebase Analytics
Интеграция Angular - Firebase Analytics
Узнайте, как настроить Firebase Analytics и отслеживать поведение пользователей в вашем приложении Angular.
0
0
930
1
Перейти к ответу Данный вопрос помечен как решенный

Ответы 1

Ответ принят как подходящий

После исследования я нашел это решение, оно сработало в моем случае:

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

Другие вопросы по теме