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!