【问题标题】:Flutter DateTime formate in Time ago in ListView.builder在 ListView.builder 中的 Time ago 中 Flutter DateTime 格式
【发布时间】:2021-08-11 09:40:48
【问题描述】:

我有 PageView.builder 小部件,它正在从我的服务器获取数据。

PageView.builder(
    itemCount: _newsList.length,
          itemBuilder: (context, index){
            if(_newsList.isNotEmpty){
            return Text(_newsList[index].posted!);
       } else Container("Empty");
}
)

我已经导入https://pub.dev/packages/timeago
但不能在PageView.builder()中使用。

请帮我整理一下。

【问题讨论】:

    标签: flutter dart flutter-layout flutter-dependencies flutter-animation


    【解决方案1】:

    要使用,请将 timeago 导入为:

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

    在小部件中使用 timeago:

    Text(timeago.format(DateTime.fromMillisecondsSinceEpoch(dateTimeMillis))); //or other DateTime object
    

    【讨论】:

    • 我收到未处理的异常:类型 'String' 不是类型 'int?' 的子类型
    • 您发布的变量的数据类型是什么?它包含什么数据?
    • 完成!先生,以前是日期时间,但现在我将其更改为字符串类型。先生,现在工作。
    • 很高兴为您提供帮助。 :)
    【解决方案2】:
     String timeAgo(DateTime fatchedDate) {
            DateTime currentDate = DateTime.now();
        
            var different = currentDate.difference(fatchedDate);
        
            if (different.inDays > 365)
              return "${(different.inDays / 365).floor()} ${(different.inDays / 365).floor() == 1 ? "year" : "years"} ago";
            if (different.inDays > 30)
              return "${(different.inDays / 30).floor()} ${(different.inDays / 30).floor() == 1 ? "month" : "months"} ago";
            if (different.inDays > 7)
              return "${(different.inDays / 7).floor()} ${(different.inDays / 7).floor() == 1 ? "week" : "weeks"} ago";
            if (different.inDays > 0)
              return "${different.inDays} ${different.inDays == 1 ? "day" : "days"} ago";
            if (different.inHours > 0)
              return "${different.inHours} ${different.inHours == 1 ? "hour" : "hours"} ago";
            if (different.inMinutes > 0)
              return "${different.inMinutes} ${different.inMinutes == 1 ? "minute" : "minutes"} ago";
            if (different.inMinutes == 0) return 'Just Now';
        
            return fatchedDate.toString();
          }
    

    【讨论】:

    • 我收到未处理的异常:“字符串”类型不是“日期时间”类型的子类型?
    猜你喜欢
    • 2014-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-24
    • 2011-04-12
    • 1970-01-01
    • 2021-05-26
    • 2020-07-02
    相关资源
    最近更新 更多