简体   繁体   中英

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"

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

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

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