vlladislav45
vlladislav45

Reputation: 83

Get all documents from a Firestore collection in Flutter

I tried with different ways but i can't edit the structure of code

//First way
QuerySnapshot querySnapshot = await db.firestoreInstance.collection('user-history').get();
    var list = querySnapshot.docs;
    print('MY LIST ===== $list');

//Second way
    final CollectionReference collectionRef = db.firestoreInstance
        .collection(historyCollection);

    print('MY SECOND LIST ===== $list');
    collectionRef.get().then((qs) {
      qs.docs.forEach((element) {
        print('MY doc id ${element.id}');
      });
    });

In my firebase collection(historyCollection) i have four documents but the debugger returns me empty array []. Is there another way to call all documents in certain collection through flutter? I'm trying to call this method through FutureBuilder component.

My version of firestore is: "cloud_firestore: ^0.16.0+1"

Upvotes: 1

Views: 5814

Answers (2)

vlladislav45
vlladislav45

Reputation: 83

The entire problem was not from these fragments of code. This problem is came out from this that my collections have subcollections. I read about this and i understand that subcollections can live without their ancestors and the only way to access parents is to do this is directly specify the exact path and name of the document. To work this code in my case was needed to add dummy components of my entire set of collections. For more information please look up these two topics:

  1. -> https://firebase.google.com/docs/firestore/using-console
  2. -> Firestore DB - documents shown in italics

Upvotes: 1

Momar
Momar

Reputation: 179

This should do the trick:

Future<List<dynamic>> getCollection(CollectionReference collection) async {
    try {
      QuerySnapshot snapshot = await collection.get();
      List<dynamic> result =  snapshot.docs.map((doc) => doc.data()).toList();
      return result;
    } catch (error) {
      print(error);
      return null;
    }
  }

Upvotes: 2

Related Questions