How to get a random document like TikTok does? That is, let's say, I pressed the button and some random record from the database seemed to me.
-
check this [link](https://stackoverflow.com/questions/46798981/firestore-how-to-get-random-documents-in-a-collection) – 3ameration Sep 02 '22 at 20:39
2 Answers
I believe you'll have to implement that yourself, based on a random index that fall inside the length of documents in your collection, then just pull it.
Kind of like:
// first get a snapshot of your collection
QuerySnapshot collection = await FirebaseFirestore.instance.collection('YOUR_COLLECTION').get();
// based on how many documents you have in your collection
// just pull one random index
var random = Random().nextInt(collection.docs.length);
// then just get the document that falls under that random index
DocumentSnapshot randomDoc = collection.docs[random];

- 2,499
- 1
- 14
- 7
TL;DR: There is no out of the box support for it from Firebase.
There is a great answer to this question over here. It explains multiple different concepts that you can do.
I will explain two ways that I can think of that is valuable and can work for you.
pre: You will be needing to keep an array of data to keep track of which data has been visited before, so you do not see them.
Depending on the traffic of your data, I would recommend, fetching all documents to local and fetch those information in random format within the docs that has been received.
You can assign an id to each document by using either integers or a uuid by using a package like this. You can keep the document ids in one separate document and fetch it first, after that fetch the document with id randomly by getting a random id out of the collection.

- 3,284
- 2
- 22
- 33