Why does Firebase colletion().getDocuments() return null or []?

Viewed 304

I have a collection called market and it had two documents that I can confirm in firebase.

enter image description here

I am now trying to get the number of documents in that collection like this:-

getAllItemsForSell()async {
    final snapshot = await Firestore.instance.collection('market').getDocuments();
    final documents = snapshot?.documents;

    print(documents); // []

  }

The above function prints out '[]', what am I doing wrong? I looked everywhere on the internet but nothing seems to be helping.

please help? I am new to the Flutter Firebase world, thanks in advance.

3 Answers

The query is working as expected. Your "market" collection doesn't actually have any documents in it - it's completely empty. When you see a document ID in italics in the console, that's means there is no document, but there are subcollections nested under that document. The ID is there in the console so you can click through to them.

See also:

To see the number of documents in that specific collection try to get the documentId from users collection and iterate through it by passing it to market collection like this

 int sampleNum =0;
getAllItemsForSell()async {
        QuerySnapshot users =  await Firestore.instance.collection('market').getDocuments();
        for(DocumentSnapshot docs in users.documents){
          QuerySnapshot doc = await Firestore.instance.collection('market').document(docs.documentID).collection('marketPosts').getDocuments();
          sampleNum = doc.documents.length;
          //posts = doc.documents.map((doc) => Post.fromDocument(doc)).toList();
        }
        print(sampleNum.toString() +' **********');
      }

why you don't use Future<void> or any type before the function. if it dosn't work read the doc for FlutterFire here is the link https://firebase.flutter.dev/docs/firestore/usage#document--query-snapshots and i think just changing getDocuments() to get() it's maybe work,

Future<void> getAllItemsForSell()async {
    final snapshot = await 
    Firestore.instance.collection('market').getDocuments();
    final documents = snapshot?.documents;

    print(documents); // []

  }
Related