简体   繁体   中英

how to model a firestore document along with its sub collection with flutter?

I have a project where i have a collection of questions and each question have a collection of answers.

I want to retrieve each questions with its answers

here is a picture of my firestore data

在此处输入图像描述

I have the class below i just dont know how to fetch the answers on the same model

class Question {
  final String id;
  final String userID;
  final String question;
  final Timestamp timestamp;
  // how can i retrieve the answers ?
  final List<Answers> answers;

  Question({this.timestamp, this.id, this.userID, this.question});

  Question.fromMap(Map snapshot, String id)
      : id = id ?? '',
        userID = snapshot['userID'] ?? '',
        question = snapshot['question'] ?? '',
        timestamp = snapshot['timestamp'] ?? Timestamp.fromDate(DateTime(2020));

  toJson() {
    return {
      "userID": userID,
      "question": question,
    };
  }
}

to fetch the questions i use

List<Question> list;
final Firestore _db = Firestore.instance;

StreamBuilder<QuerySnapshot>(
        stream:  _db.collection("questions").snapshots(),
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            list = snapshot.data.documents
                .map((doc) => Question.fromMap(doc.data, doc.documentID))
                .toList();
          }
          return ListView.builder(
              itemCount: list.length,
              itemBuilder: (context, index) => ListTile(
                    title: Text(list[index].question),
                  ));
        },
      ),

Your answers are stored in a subcollection, and you will need to build a CollectionReference to that subcollection to query it.

_db
    .collection("questions")
    .document(questionId)
    .collection("answers")

Querying that will give you all the answers for the provided questionId.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM