spongyboss
spongyboss

Reputation: 8666

Flutter Firestore Nested Query

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

Upvotes: 0

Views: 4258

Answers (2)

Jobel
Jobel

Reputation: 643

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

Upvotes: 1

Frank van Puffelen
Frank van Puffelen

Reputation: 598728

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.

Upvotes: 4

Related Questions