实际上从dart 2.6.0就开始支持扩展函数了
如果pubspec.yaml中设置的dart版本低于2.6.0则会出现警告提示
如:
environment:
sdk: “>=2.1.0 ❤️.0.0”
警告提示:
Extension methods weren’t supported until version 2.6.0
先来定义一个扩展函数
extension WidgetExt on Widget {
Container intoContainer({
//复制Container构造函数的所有参数(除了child字段)
Key key,
AlignmentGeometry alignment,
EdgeInsetsGeometry padding,
Color color,
Decoration decoration,
Decoration foregroundDecoration,
double width,
double height,
BoxConstraints constraints,
EdgeInsetsGeometry margin,
Matrix4 transform,
}) {
//调用Container的构造函数,并将当前widget对象作为child参数
return Container(
key: key,
alignment: alignment,
padding: padding,
color: color,
decoration: decoration,
foregroundDecoration: foregroundDecoration,
width: width,
height: height,
constraints: constraints,
margin: margin,
transform: transform,
child: this,
);
}
}
现在,所有widget对象都多了一个intoContainer(...)
扩展函数,而且参数与Container
构造方法一致,于是,我们就可以这样写了: