B. Mercan
B. Mercan

Reputation: 51

Flutter firestore fetch nested collections all data

im building an reporting app,

when a report sent to database its saves like

events(collection) -> New York(doc) -> Manhattan(col) -> Central Park(doc) -> event(col) -> saved documents

its basically saves, events to city to district to street to event

i fetch data of user with no problem

Stream<QuerySnapshot> tasks = FirebaseFirestore.instance
        .collection('events')
        .doc(StoredData.getCity()) //current users city information
        .collection(StoredData.getDistrict().toString()) //current users district information
        .doc(StoredData.getStreet()) //current users street information
        .collection('events')
        .where('uid', isEqualTo: FirebaseAuth.instance.currentUser?.uid) //query uid in documents uid field
        .snapshots(); 

here is my problem

i want to fetch all data of city but i cant figure out how to do that. i want to see all records of new york

Upvotes: 2

Views: 3334

Answers (2)

DevMukh
DevMukh

Reputation: 29

final String productId;  
return StreamBuilder<QuerySnapshot>(
      stream: FirebaseFirestore.instance
          .collection('Products')
          .doc(widget.productId) // Use the provided productId
          .collection('Pak')
          .snapshots(),
      builder: (context, snapshot) {
        if (snapshot.hasError) {
          return const SnackBar(
              content: Text('Something went wrong while loading images'));
        }
        if (snapshot.connectionState == ConnectionState.waiting) {
          return const Center(
            child: CircularProgressIndicator(
              color: Colors.deepOrange,
            ),
          );
        }
        var docs = snapshot.data!.docs;
        return Row(
          children: [
            for (var i = 0; i < docs.length; i++)
              Container(
                margin: const EdgeInsets.only(right: 20),
                height: 200,
                width: 200,
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(20),
                  image: DecorationImage(
                    image: NetworkImage(docs[i]['image']),
                    fit: BoxFit.cover,
                  ),
                ),
              ),
          ],
        );
      },
    );
    You have to just pass the id of your collection and then access the subCollection to fetch data

Upvotes: 0

Frank van Puffelen
Frank van Puffelen

Reputation: 598668

Firestore can only return data from a single collection at a time, or from multiple collections with the same name by using a collection group query. You can use the latter to get for example all documents from the event (singular) collections across all of your database, or under a specific path.

You can't however get the New York document and all data under it. That is simply not how the database/data model works.

Upvotes: 4

Related Questions