How to get random documents from Cloud Firestore in Dart (for Flutter)?

ⅰ亾dé卋堺 提交于 2020-05-26 07:23:31

问题


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!


回答1:


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!



来源:https://stackoverflow.com/questions/57180123/how-to-get-random-documents-from-cloud-firestore-in-dart-for-flutter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!