Lets say I have the following documents inside a Firestore collection:
How can I randomly get one or more documents without having to download them all?
By the way, I've already seen Dan McGrath's Answer, but he didn't specifically explain how to generate the auto-id for Flutter, also, I would love to see a complete example in Dart since his explanation was very generic.
Thanks in advance!
Asked
Active
Viewed 1,702 times
3

ThiagoAM
- 1,432
- 13
- 20
-
There is no autoId generator inside the firestore sdk that you can use. But you can see (and copy) the implementation here: https://github.com/flutter/plugins/blob/master/packages/cloud_firestore/lib/src/utils/push_id_generator.dart – ZeRj Jul 24 '19 at 14:24
-
Those look like Realtime Database push IDs, not Firestore auto IDs. Which database are you using? – Doug Stevenson Jul 24 '19 at 15:51
-
@ZeRj That answers part of the question, however how would the query code look like? – ThiagoAM Jul 24 '19 at 16:55
-
Have you found a solution to this problem? I've come across the same issue after reading Dan's answer. – Bobthebuilder24 May 16 '20 at 20:33
-
@Bobthebuilder24 unfortunately I haven't found the solution for this problem... – ThiagoAM May 19 '20 at 14:39
-
@Bobthebuilder24 take a look at my answer. – Banana droid May 22 '20 at 03:47
1 Answers
0
According to Dan's answer, here's my current implementation.
static const AUTO_ID_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
static const AUTO_ID_LENGTH = 20;
String _getAutoId() {
final buffer = StringBuffer();
final random = Random.secure();
final maxRandom = AUTO_ID_ALPHABET.length;
for (int i = 0; i < AUTO_ID_LENGTH; i++) {
buffer.write(AUTO_ID_ALPHABET[random.nextInt(maxRandom)]);
}
return buffer.toString();
}
Code to query:
final autoId = _getAutoId();
final query = ref
.where("qId", isGreaterThanOrEqualTo: autoId)
.orderBy("qId")
.limit(count);
QuerySnapshot response = await query.getDocuments();
if (response.documents == null || response.documents.length == 0) {
final anotherQuery = ref
.where('qId', isLessThan: autoId)
.orderBy('qId')
.limit(count);
response = await anotherQuery.getDocuments();
}
Some explainations:
- qId is a field of my document. It's same as the documentId.
- This implementation is based on Bi-directional, according to Dan's answer. We still have unfairly result but I'm ok with that. If someone have better algorithm, please share.
- _getAutoId() is re-written based on Java code of firebase library.
If you have any questions, please ask. I will try to help as much as I could.
Have a nice day!

Banana droid
- 690
- 1
- 9
- 27