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

Flutter中如何格式化显示Firestore的Timestamp类型时间戳

报错根因

你代码里的类型声明和Firestore实际返回的字段类型不匹配:ordered_date字段存在部分值是字符串格式的情况,直接声明为Timestamp类型强转就会触发String is not a subtype of Timestamp/datetime报错。

修复方案

不要直接对返回字段做固定类型强转,加一层类型判断,兼容Timestamp、字符串、空值三种常见返回场景,修改后的代码如下:

itemCount: orderList.data.docs.length,
itemBuilder: (ctx, index) {
  final docData = orderList.data.docs[index].data() as Map<String, dynamic>;
  final cartOrder = docData['cartorder'];
  final delivered = docData['delivered'];

  // 多类型兼容转换为DateTime
  DateTime orderedDate;
  final dynamic rawDateValue = docData['ordered_date'];
  if (rawDateValue is Timestamp) {
    orderedDate = rawDateValue.toDate();
  } else if (rawDateValue is String) {
    orderedDate = DateTime.parse(rawDateValue);
  } else {
    // 异常/空值兜底,可根据业务需求替换默认值
    orderedDate = DateTime.now();
  }

  // 按指定格式格式化输出
  String myDate = DateFormat('dd/MM/yyyy,hh:mm').format(orderedDate);

  // 后续编写你的UI渲染逻辑即可
}
优化建议
  • 后续写入Firestore日期字段时,统一使用Timestamp.fromDate(DateTime对象)写入,不要存格式化后的日期字符串,从根源避免同字段多类型的问题。
  • 如果需要展示24小时制时间,把格式化字符串里的hh替换为HH即可,默认hh为12小时制格式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 06:30:46