平时开发中经常遇见,Button中带图片。 图片的位置还不固定。 在此封装一个。希望对你有帮助
import 'package:flutter/material.dart';
enum JCImagePossition { left, right, top, bottom }
class JCImageButton extends StatelessWidget {
final String imageAssets;
final String titleString;
final Color bgColor;
final double imageSize;
final double cornerRadius;
final double interval;
final Color titleColor;
final double titleSize;
final FontWeight fontweight;
final JCImagePossition possiton;
late final VoidCallback callBack;
late final EdgeInsetsGeometry padding;
JCImageButton(
{
// 背景颜色 圆角
this.bgColor = Colors.blue,
this.cornerRadius = 2,
// 图片路劲 大小
this.imageAssets = "",
this.imageSize = 16,
// 字体
this.titleString = "",
this.titleColor = Colors.white,
this.titleSize = 16,
this.fontweight = FontWeight.w400,
// 文字和图片间隔、 padding
this.interval = 8,
EdgeInsetsGeometry? padding,
// 位置 回调
this.possiton = JCImagePossition.left,
VoidCallback? callBack, // 回调
}) {
this.padding = padding ?? EdgeInsets.fromLTRB(72, 8, 72, 8);
this.callBack = callBack ??
() {
print("默认回调");
};
}
@override
Widget build(BuildContext context) {
return Container(
alignment: Alignment.center,
padding: this.padding,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(this.cornerRadius),
color: this.bgColor,
),
child: TextButton(
style: ButtonStyle(
overlayColor: MaterialStateProperty.all(Colors.transparent)),
onPressed: () {
this.callBack();
},
child:
(this.possiton == JCImagePossition.top || this.possiton == JCImagePossition.bottom)
? _getTopAndBottomPosstionWidget(this.possiton == JCImagePossition.top)
: _getLeftAndRightPosstionWidget(this.possiton == JCImagePossition.left)
),
);
}
Widget _getTopAndBottomPosstionWidget(bool isTop) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: isTop
? [ _getImage(), Container(height: this.interval,), _getTitle()]
: [ _getTitle(), Container(height: this.interval,), _getImage()]
);
}
Widget _getLeftAndRightPosstionWidget(bool isLeft) {
return Row(
mainAxisAlignment: MainAxisAlignment.center,
children: isLeft
? [ _getImage(), SizedBox(width: this.interval), _getTitle()]
: [ _getTitle(), SizedBox(width: this.interval), _getImage()]
);
}
Widget _getImage() {
return Image.asset(
'${this.imageAssets}',
width: this.imageSize,
height: this.imageSize,
);
}
Widget _getTitle() {
return Text(
'${this.titleString}',
style: TextStyle(
color: this.titleColor,
fontSize: this.titleSize,
fontWeight: this.fontweight),
);
}
}
调用、那就简单了。
JCImageButton(
callBack: () {
_checkUpdate();
},
titleString: "有新版本可用,请及时更新",
imageAssets: "assets/images/wn_update_version_icon.png",
possiton: JCImagePossition.left,
bgColor: ColorUtils.hexColor(0x2680FF),
)