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

Flutter 如何在 PageView.builder 中用 timeago 格式化 DateTime 为相对时间

实现方案

步骤1:导入依赖并初始化中文配置

首先在你要使用该功能的dart文件头部导入timeago包,如果需要展示中文相对时间,需要提前注册中文 locale 配置,建议放在页面的initState生命周期中执行:

import 'package:timeago/timeago.dart' as timeago;

@override
void initState() {
  super.initState();
  // 注册中文相对时间配置,不需要中文的话可以跳过这行
  timeago.setLocaleMessages('zh_CN', timeago.ZhCnMessages());
}

步骤2:修改PageView.builder中的时间渲染逻辑

你需要先把服务端返回的posted时间字符串解析为DateTime类型,再传入timeago的format方法即可得到「多久以前」的相对时间格式,修改后的完整代码如下:

PageView.builder(
  itemCount: _newsList.length,
  itemBuilder: (context, index) {
    if (_newsList.isNotEmpty) {
      // 先解析服务端返回的时间字符串为DateTime
      DateTime postTime = DateTime.parse(_newsList[index].posted!);
      // 格式化得到相对时间,传入locale: 'zh_CN'返回中文结果
      String relativeTime = timeago.format(postTime, locale: 'zh_CN');
      return Text(relativeTime);
    } else {
      return const Text("Empty");
    }
  }
)

注意事项

  • 如果服务端返回的时间格式无法被DateTime.parse直接解析,可以先使用intl包的DateFormat类自定义格式解析后再传入timeago处理
  • 注意添加空判断逻辑,避免时间字段为null时出现解析崩溃

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.19 12:36:04