如何从Dart的Cloud Firestore获取随机文档(适用于Flutter)? [英] How to get random documents from Cloud Firestore in Dart (for Flutter)?

查看:96
本文介绍了如何从Dart的Cloud Firestore获取随机文档(适用于Flutter)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在Firestore集合中有以下文档:



如何随机获得一个或更多文件而不必全部下载?


顺便说一句,我已经看过 Dan McGrath的答案,但是他没有具体说明如何为Flutter生成自动ID,而且,我希望看到Dart中的完整示例,因为他的解释非常通用。


预先感谢!

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!

推荐答案

根据Dan的回答,这是我当前的实现。

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();
  }

要查询的代码:

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();
}

一些解释:


  1. qId是我文档的一个字段。

  2. 根据Dan的
    答案,此实现基于双向。我们仍然有不公平的结果,但我可以接受。如果有人有更好的算法,请分享。

  3. _getAutoId()是根据firebase库的Java代码重写的。

如有任何疑问,请询问。我会尽力提供帮助。

If you have any questions, please ask. I will try to help as much as I could.

祝你有美好的一天!

这篇关于如何从Dart的Cloud Firestore获取随机文档(适用于Flutter)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆