3

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.

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
  • Why are you expecting something different? Empty array makes total sense for an empty collection, but we can't see if that's the case. Please edit the question to explain what you are expecting, perhaps showing a screenshot of the documents you intended to receive. – Doug Stevenson Nov 01 '20 at 00:56

3 Answers3

1

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:

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
1

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() +' **********');
      }
dagmawi tadesse
  • 134
  • 1
  • 7
0

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); // []

  }
ahmed
  • 444
  • 2
  • 9
  • 1
    I still get the same problem, and using 'get()' throws an error "The method 'get' isn't defined for the type 'CollectionReference'." – Photo Genic Nov 01 '20 at 00:33