颤动| 如何从 Firestore 获取对象列表?

F. *_*lem 1 firebase flutter google-cloud-firestore

这是我的问题对象:

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

  Question(String q, bool a, String ca) {
    text = q;
    answer = a;
    correctAnswer = ca;
  }
}
Run Code Online (Sandbox Code Playgroud)

我想从 Firestore 获取问题列表,如下所示:

List<Question> questionBank = [];
Run Code Online (Sandbox Code Playgroud)

Firestore 看起来像这样: firestore

我怎样才能做到这一点?

hnn*_*lch 5

从 Cloud Firestore 检索问题并转换为列表:

  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;
  }
Run Code Online (Sandbox Code Playgroud)

将 fromMap 方法添加到 Question 类:

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'
    );
  }
}
Run Code Online (Sandbox Code Playgroud)