核心思路就是你想要什么就返回什么需要padding就写返回padding的方法,需要BoxDecoration就写返回BoxDecoration的方法,需要一个文本效果就返回一个Text,需要什么就写个方法return什么,可以写一个类,也可以写一个类里面的方法,可以返回就可以了
//写一个类,继承没状态,传一个距离进来,返回Padding是最关键的
class TopPadding extends StatelessWidget {
TopPadding(this.topPadding, {Key? key}) : super(key: key);
double topPadding;
@override
Widget build(BuildContext context) {
return Padding(padding: EdgeInsets.only(top: topPadding));
}
}
调用就是使用该类,传距离
TopPadding(12),
//写一个类,里面写多个方法
class BoxDecorationUtil {
///设置背景
BoxDecoration setFillBoxDecoration(color, radius,
{topLeft, topRight, bottomLeft, bottomRight}) {
return BoxDecoration(
//背景
color: color,
//设置四周圆角 角度
borderRadius: radius == 0.0
? BorderRadius.only(
topLeft: Radius.circular(topLeft ?? 0),
topRight: Radius.circular(topRight ?? 0),
bottomLeft: Radius.circular(bottomLeft ?? 0),
bottomRight: Radius.circular(bottomRight ?? 0))
: BorderRadius.all(Radius.circular(radius)));
}
///设置背景图片
BoxDecoration setFillBoxDecorationImg(bgUrl,
{fit, topLeft, topRight, bottomLeft, bottomRight}) {
return BoxDecoration(
//设置四周圆角 角度
borderRadius: BorderRadius.only(
topLeft: Radius.circular(topLeft ?? 0),
topRight: Radius.circular(topRight ?? 0),
bottomLeft: Radius.circular(bottomLeft ?? 0),
bottomRight: Radius.circular(bottomRight ?? 0)),
image: DecorationImage(
fit: fit ?? BoxFit.fill,
image: const BackgroundWall().loadImagesProvider(bgUrl)));
}
}
正常写代码是
Container(
decoration: BoxDecoration(//直接写BoxDecoration()
borderRadius:
BorderRadius.circular(50),
border: Border.all(
width: 2.r,
color: Colors.white)),
child: PhysicalModel(
color: Colors.transparent,
borderRadius:
BorderRadius.circular(50),
clipBehavior: Clip.antiAlias,
child: Image(
image: AssetImage(
avatarList[index],
),
width: 79.r,
height: 79.r)),
);
而使用封装好的类方法就是
Container(
decoration: BoxDecorationUtil()
.setFillBoxDecoration(Colors.white, 14.0),margin: const EdgeInsets.only(top: 35, right: 52, left: 52),)
文字居中的方法
class ContentCenterText extends StatelessWidget {
ContentCenterText(this.contentText, this.contentSize, this.color,
{Key? key, this.height = 1.2})
: super(key: key);
String contentText;
double contentSize;
double height;
Color color;
@override
Widget build(BuildContext context) {
return Text(contentText,
textAlign: TextAlign.center,
style: TextStyle(color: color, fontSize: contentSize, height: height));
}
}