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
晚來天欲雪,能飲一杯無?開發