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

Flutter中使用DateTime查询Realm时遭遇无效谓词错误

问题解决:Realm DateTime字段查询语法错误

错误原因

直接将DateTime对象拼接进查询语句时,生成的字符串格式(如2022-12-29 17:20:25.830699)不符合Realm查询谓词的语法要求:日期字面量需要用引号包裹,且不能存在未被解析的分隔符。

解决方案

方案1:使用ISO8601字符串并包裹引号

将DateTime转为标准ISO8601格式字符串,并用引号包裹后拼接:

RealmResults<Exercise> todoExercise() {
  DateTime date = DateTime.now();
  final isoDate = date.toIso8601String();
  final results = realm.query<Exercise>('due >= "$isoDate"');
  return results;
}

方案2:使用参数绑定(推荐)

通过占位符传递参数,让Realm自动处理日期格式,避免字符串拼接的语法问题,同时更安全:

RealmResults<Exercise> todoExercise() {
  DateTime date = DateTime.now();
  final results = realm.query<Exercise>('due >= @0', [date]);
  return results;
}

验证说明

两种方法都能正确筛选出due字段大于等于当前日期的Exercise对象,符合你预期返回3条结果的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 22:15:27