0

Is there a way to read a nested collection in Firestore using Flutter? I have the following data structure

Users:
 - userId:
     - name: value,
     - surname: value;
     - addresses:
         - addressId:
              - street:value,
              - city: value

I can read the first collection with the following code:

Firestore.instance.collection("users").document("userId")
        .snapshots().listen((snapShot) {});

Is there a way for me to access the addresses from the code above or must I run another command that directly gets the addresses like below:

Firestore.instance.collection("users").document("userId").
        collections("addresses").snapshots().listen((snapShot) {});
spongyboss
  • 8,016
  • 15
  • 48
  • 65
  • Firestore.instance .collection('abc') .document("aa") . collection('xyz') .getDocuments() .then((QuerySnapshot snapShot) { snapShot.documents.forEach((doc) { print('${doc.documentID}'); print(('${ei.data['name of your field']}')); }); }); – Speedy11 Dec 13 '19 at 14:45

2 Answers2

4

Reading a document from Firestore does not automatically read data from subcollections of that document. If you want the data from the subcollections, you willl need to do an additional read for that.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
1

I am reading a nested collection in Firestore to populate an Expansion widget. See my solution in https://stackoverflow.com/a/51057195/5013735

The trick is in to create a structure like:

  List<Widget> _getChildren() {
    List<Widget> children = [];
    documents.forEach((doc) {
      children.add(
        ProjectsExpansionTile(
          name: doc['name'],
          projectKey: doc.documentID,
          firestore: firestore,
        ),
      );
    });
    return children;
  }
Jobel
  • 633
  • 6
  • 13