先看一篇文章让 Text.rich 水平方向居中
根据文章观点我实现了3种
//金额:xxx元/万+ ,例如 "55万+"或 "5500元"
Widget buildItemFormatText1(String amount, {bool isTop = false}) {
String unit = "";
if (amount.contains("万+")) {
unit = "万+";
} else if (amount.contains("元")) {
unit = "元";
}
return RichText(
text: TextSpan(
text: amount.replaceAll(unit, ''),
style: TextStyle(
fontSize: isTop ? 37 : 33,
fontWeight: FontWeight.w600,
color: Colors.red,
), // 设置初始字体大小
children: [
TextSpan(
text: unit,
style: TextStyle(
fontSize: isTop ? 28 : 24,
fontWeight: FontWeight.bold,
), // 设置单位的字体大小较小
),
],
),
);
}
结果不能居中对齐
Widget buildItemFormatText2(String amount, {bool isTop = false}) {
String unit = "";
if (amount.contains("万+")) {
unit = "万+";
} else if (amount.contains("元")) {
unit = "元";
}
return DefaultTextStyle(
style: TextStyle(
fontSize: isTop ? 24 : 22,
color: Colors.red,
fontWeight: FontWeight.w600,
),
child: Row(
mainAxisAlignment: MainAxisAlignment.start,
children: [
Text(
amount.replaceAll(unit, ''),//金额
style: TextStyle(
fontSize: isTop ? 37 : 33,
fontWeight: FontWeight.bold,
),
),
Text(unit),//单位
],
),
);
}
结合文章开头介绍的作者提供的方法,加上第一种富文本,就有了第三种方法
Widget buildItemFormatText(String amount, {bool isTop = false}) {
String unit = "";
if (amount.contains("万+")) {
unit = "万+";
} else if (amount.contains("元")) {
unit = "元";
}
return RichText(
text: TextSpan(
text: amount.replaceAll(unit, ''),
style: TextStyle(
fontSize: isTop ? 37 : 33,
fontWeight: FontWeight.w600,
color: Colors.red,
), // 设置初始字体大小
children: [
WidgetSpan(
alignment: PlaceholderAlignment.middle,
child: Text(
unit,
style: TextStyle(
color: Colors.red,
fontSize: isTop ? 28 : 24,
fontWeight: FontWeight.bold,
),
),
),
],
),
);
}