CTT Worker
CTT Worker

Reputation: 97

Firebase Firestore get all Docs is empty in Flutter

I want to get all sub docs and collections from the collection.

Database structure:

Code Snippet:

_firestore.collection("messages").get().then((querySnapshot) => {getdata(querySnapshot)});

But querySnapshot.docs.length is always zero. How can I try to get all data from collection?

Upvotes: 0

Views: 876

Answers (1)

Johnny Nguyen
Johnny Nguyen

Reputation: 11

Hrmmm what does your current doc query look like?

The id of your documents are a bit confusing, but I'd assume the standard query should work.

NOTE : Using sequential keys/numbers as document and collections ID's is dangerous and will give you a lot of problems later down the line. If you're not generating unique-ids yourself, let Firestore do it for you. Firebase - best practices

E.g.

To listen to the changes of the messages/2/1 collection:

 final snapshotStream = FirebaseFirestore.instance
        .collection('messages/2/1')
        .snapshots()
        .asBroadcastStream();

This returns a stream which contains a snapshot of each of the documents in there that will be updated in 'real-time'. The .asBroadCastStream() ensures that you can register multiple listeners to that stream. (Looks like you're using this as some sort of chat feature?)

A little extra, one way to access all the documents within the stream:

 await for (final streamSnapshot in snapshotStream) {
          final documentsList = streamSnapshot.docs;
          /// Do something with documentsList
 }

Let me know how it goes, good luck! :)

Upvotes: 1

Related Questions