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------------------

绿蚁新醅酒,红泥小火炉。 

晚来天欲雪,能饮一杯无

12-07 10:22