【问题标题】:How do i limit the number of documents from Firebase with dates in Flutter如何限制 Firebase 中带有 Flutter 日期的文档数量
【发布时间】:2020-12-13 20:16:44
【问题描述】:

我正在构建一个颤振应用程序,它通过 firebase cloud firestore 获取文档,但我希望它只显示当天编写的文档。就像我添加到集合中一样,它只会返回今天的文档。请帮忙

Container(
              height: MediaQuery.of(context).size.height,
              child: StreamBuilder<QuerySnapshot>(
                  stream: Firestore.instance.collection('all').snapshots(),
                  builder: (context, snapshot) {
                    if (!snapshot.hasData) {
                      return Text('.....Loading');
                    }
                    return ListView.builder(
                        scrollDirection: Axis.vertical,
                        itemCount: snapshot.data.documents.length,
                        itemBuilder: (context, index) {
                          DocumentSnapshot all = snapshot.data.documents[index];
                          return Container(
                           child: Row(
                             mainAxisAlignment: MainAxisAlignment.spaceAround,
                             children: [
                               Column(
                                 children: [
                                   Text('10:00', style: TextStyle(fontSize: 18),),
                                   SizedBox(height: 3,),
                                   Text('05 Sep', style: TextStyle(fontSize: 13),),
                                 ],
                               ),
                               Column(
                                 crossAxisAlignment: CrossAxisAlignment.start,
                                 children: [
                                   Text('Europa league', style: TextStyle(fontSize: 15),),
                                   SizedBox(height: 2,),
                                   Text( '${all['gg']['home']} vs ${all['gg']['away']}', style: TextStyle(fontSize: 18, fontWeight: FontWeight.w500),),

【问题讨论】:

标签: database firebase flutter dart google-cloud-firestore


【解决方案1】:

您只需要像这样在查询上放置一个 where 子句(这给出了过去 24 小时内所做的任何事情):

Firestore.instance
  .collection("all")
  .where("created_date", isGreaterThan: DateTime.now().subtract(Duration(days: 1)) )
  .snapshots();

确保您的数据有日期,插入时您可以这样做:

Firestore.instance
  .collection("all")
  .add({
    'data': "data",
    'created_date' : FieldValue.serverTimestamp(),
  });

【讨论】:

  • 我完全是新手,我不太懂
  • 谢谢 Jan 但我尝试过并上传了一个新文档,但数据库没有返回任何内容
  • 我想要这样一种情况,即我将一个文档上传到我的收藏中,并且它整天都在屏幕上 示例,如果我在星期一早上上传,它只会在整个星期一停留,直到我写另一个周二的文件
  • 我的 Cloud Firestore 文档中会有时间戳字段吗?
  • 是的,您需要在 Cloud Firestore 文档中添加一个时间戳字段。添加文档时,请确保给它一个日期,在我的示例中,我将字段称为“created_date”并指示firestore将该值设置为服务器当前时间戳。当你去检索你的文档时,你需要从一个集合中选择(你已经完成了),然后添加一个“where子句”,它将结果过滤到特定的日期范围。在我的示例中,它正在过滤集合中具有“created_date”值大于(较新)1 天(即 24 小时)的集合中的每个文档。
猜你喜欢
  • 1970-01-01
  • 2022-10-15
  • 2018-07-15
  • 1970-01-01
  • 2014-08-20
  • 2017-08-12
  • 1970-01-01
相关资源
最近更新 更多