dart的extension方法能够给已经存在的类添加新的函数,经过extension咱们能够封装一些经常使用方法,提升开发效率。html
给string添加一个log打印方法ide
extension StringExt on String { void log() { print('--------$this'); } }
使用函数
"there is something need to print".log();
iconfont中的图标有偏下的问题,添加一个iconCenter方法,使icon居中this
extension WidgetExt on Widget { Widget iconCenter(double size) { return Baseline( baselineType: TextBaseline.ideographic, baseline: size * 0.84, child: this, ); } }
使用spa
Icon(KIconData.trash, size: 16.w, color: Colors.black).iconCenter(16.w),
例子同上一篇写的处理时间戳的例子(http://www.javashuo.com/article/p-xnxrfowa-nx.html)code
extension TimeExt on num { String get publishTime { var now = new DateTime.now(); var longTime = this.toString().length < 13 ? this * 1000 : this; var time = new DateTime.fromMillisecondsSinceEpoch(longTime); var difference = now.difference(time); int days = difference.inDays; int hours = difference.inHours; int minutes = difference.inMinutes; String result = ''; if (days > 3) { bool isNowYear = now.year == time.year; var pattern = isNowYear ? 'MM-dd' : 'yyyy-MM-dd'; result = new DateFormat(pattern).format(time); } else if (days > 0) { result = '$days天前'; } else if (hours > 0) { result = '$hours小时前'; } else if (minutes > 0) { result = '$minutes分钟前'; } else { result = '刚刚'; } return result; } }
使用,轻松获取发布时间orm
1607260860000.publishTime();
END------------------htm
绿蚁新醅酒,红泥小火炉。 blog
晚来天欲雪,能饮一杯无?开发