3

Lets say I have the following documents inside a Firestore collection: enter image description here
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!

ThiagoAM
  • 1,432
  • 13
  • 20

1 Answers1

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:

  1. qId is a field of my document. It's same as the documentId.
  2. 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.
  3. _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