dart的extension方法可以給已經存在的類新增新的函式,通過extension我們可以封裝一些常用方法,提高開發效率。
例一:擴充套件String
給string新增一個log列印方法
extension StringExt on String { void log() { print('--------$this'); } }
使用
"there is something need to print".log();
例二:擴充套件Widget
iconfont中的圖示有偏下的問題,新增一個iconCenter方法,使icon居中
extension WidgetExt on Widget { Widget iconCenter(double size) { return Baseline( baselineType: TextBaseline.ideographic, baseline: size * 0.84, child: this, ); } }
使用
Icon(KIconData.trash, size: 16.w, color: Colors.black).iconCenter(16.w),
例三:擴充套件number
例子同上一篇寫的處理時間戳的例子(https://www.cnblogs.com/MaiJiangDou/p/14060017.html)
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; } }
使用,輕鬆獲取釋出時間
1607260860000.publishTime();
END------------------
綠蟻新醅酒,紅泥小火爐。
晚來天欲雪,能飲一杯無?