You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中能否根据DateTime值查询Firebase Firestore文档?

实现方案

首先明确查询逻辑:你需要的「当前时间早于到达日期」等价于「到达日期 > 当前时间」,直接用Firestore的isGreaterThan查询条件即可实现,分两种场景处理:

  1. 若arrival date字段是Firestore原生Timestamp类型/标准ISO 8601格式字符串
    直接传当前DateTime对象查询即可,注意字段名要和Firestore中存储的完全一致(你截图里的字段名带空格,不要写成arrivalDate):
FirebaseFirestore.instance
    .collection('Patients')
    .where('arrival date', isGreaterThan: DateTime.now())
    .snapshots();

如果需要和之前的translator条件组合查询,写法如下:

FirebaseFirestore.instance
    .collection('Patients')
    .where('translator', isEqualTo: _auth.currentUser!.displayName)
    .where('arrival date', isGreaterThan: DateTime.now())
    .snapshots();

注:多条件组合查询需要提前创建对应索引,第一次运行时控制台会输出包含索引创建链接的报错,点击链接按提示操作即可完成索引创建,耗时仅几秒。

  1. 若arrival date字段是自定义格式的日期字符串(如2024/05/20、05-20-2024)
    需要先将当前时间转换为和存储格式完全一致的字符串,再传入查询条件,示例如下(以yyyy-MM-dd格式为例):
// DateFormat来自intl包,需要先在pubspec.yaml中引入依赖
String formattedNow = DateFormat('yyyy-MM-dd').format(DateTime.now());
FirebaseFirestore.instance
    .collection('Patients')
    .where('arrival date', isGreaterThan: formattedNow)
    .snapshots();

注:如果你的字符串格式不是时间先后和字典序一致的格式(比如MM-dd-yyyy),无法直接用Firestore查询,建议将字段类型修改为Firestore原生Timestamp类型,后续查询和处理效率更高。

内容的提问来源于stack exchange,提问作者Njm Jeb

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 23:36:02