Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter Firebase How to get random document

I am trying to get some random posts from Firebase. But i am unable to get random document id.

Is there any way to retrieve data from Firebase like this :-

  getRandomData() async {
QuerySnapshot snapshot = await posts
    .document(random.id)
    .collection('userPosts')
    .getDocuments();}

i am trying to say that. Now i am able to get documentID normally not in italics.so now how can i get random documentID from Firebase.

enter image description here

like image 660
Chinmaya Garnaik Avatar asked Oct 15 '25 17:10

Chinmaya Garnaik


2 Answers

List documentIds in a list first.

var list = ['documentId1','documentId2','documentId3'];

var element = getRandomElement(list);

Then query the documentSnapshot

like image 121
Subair K Avatar answered Oct 18 '25 11:10

Subair K


The main problem here that's going to prevent you from moving forward is the fact that you don't actually have any documents nested immediately under "posts". Notice that the names of the documents are in italics. That means there isn't actually a document here at all. The reason why they are show, however, is because you have a subcollection "userPosts" nested under the path where that document ID exists.

Since you don't have any documents at all under "posts", the usual strategies to find a random document won't work at all. You're going to have to actually populate some data there to select from, or find another way to select from the data in the subcollections.

like image 42
Doug Stevenson Avatar answered Oct 18 '25 10:10

Doug Stevenson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!