在最近flutter页面改造过程中,发现通过Contail包裹Text控件设置上下padding时,在华为魅族和vivo等手机上并没有居中展示,所以通过查看控件属性,得以解决此类问题
可以看到上面的在华为手机上明显偏下了
Container(
padding: EdgeInsets.only(left: 4,top: 2,bottom: 2,right: 4),
color: Colors.blue,
child: Text('测试标题111'),
),
Container(
color: Colors.blueAccent,
padding: EdgeInsets.only(left: 4,top: 2,bottom: 2,right: 4),
margin: EdgeInsets.only(top: 4),
child: ExText(
'测试标题111',
TextStyle(fontSize: 14, color: Colors.redAccent),
maxLines: 2,
textAlign: TextAlign.left,
),
),
下面是代码
/// 修正不同手机上leading和不居中的问题
class ExText extends StatelessWidget {
final String data; // 展示文案
final TextStyle textStyle; // 文字样式 由于字体大小和颜色是必须的 所以此处为必穿参数
final int maxLines; //最大行数
final double height; // 文本高度 默认1.1更居中 但随着字体变大 这个值应该趋于1.0 允许手动调节
final TextOverflow overflow; //裁剪模式
final double textMaxWidth; // 文字能显示的最大宽度 如果 为autoFixSize则需要指定该值
final TextAlign textAlign; // 对齐方式
ExText(
this.data,
this.textStyle, {
this.maxLines = 1,
this.height = 1.1,
this.overflow = TextOverflow.ellipsis,
this.textMaxWidth = double.infinity,
this.textAlign = TextAlign.center
});
@override
Widget build(BuildContext context) {
// 如果需要修正大小
return Text(
data,
maxLines: maxLines,
textAlign: textAlign,
style: textStyle,
strutStyle: StrutStyle(
fontSize: textStyle.fontSize,
fontWeight: textStyle.fontWeight,
leading: 0,
height: height,
// 1.1更居中
forceStrutHeight: true, // 关键属性 强制改为文字高度
),
textHeightBehavior: TextHeightBehavior(
// 基线 发现不设置也能行
applyHeightToFirstAscent: false,
applyHeightToLastDescent: false),
);
}
}
关键点也已经标出。
也可以引入我已经打包好的flutter插件
https://pub.flutter-io.cn/packages/flutter_ex_widget
上面有一些比较通用的功能控件