Flutter | How to get a List of Objects from Firestore?

Viewed 2435

This is my Question Object:

class Question {
  String text;
  String correctAnswer;
  bool answer;

  Question(String q, bool a, String ca) {
    text = q;
    answer = a;
    correctAnswer = ca;
  }
}

I want to get a List of Questions from Firestore like so:

List<Question> questionBank = [];

Firestore looks like this: firestore

How can i achieve this?

2 Answers

Retrieve questions from Cloud Firestore and convert to list:

  Future<List<Question>> fetchQuestions(String userId) async {
    final questions = new List<Question>();
    final doc = await FirebaseFirestore.instance.collection('Questions').doc(userId).get();
    final questionsTmp = doc.data().questions;
    questionsTmp.forEach((questionTmp) {
      questions.add(Question.fromMap(questionTmp));
    });
    return questions;
  }

Add fromMap method to Question class:

class Question {
  String text;
  String correctAnswer;
  bool answer;

  Question(String q, bool a, String ca) {
    text = q;
    answer = a;
    correctAnswer = ca;
  }

  static Question fromMap(Map<String, dynamic> map) {
    return Question(
      map['text'],
      map['answer'],
      map['correctAnswer'].ToString() == 'true'
    );
  }
}
Related