如何使文本采用基于颤振字符串长度的固定宽度?



我有一个小部件树如下:

Widget example() {
return Column(
children: [
Row(
children: [
Expanded(
child: Container(
height: 100,
decoration: BoxDecoration(color: Colors.red),
),
),
Text('25.00%')
],
),
Row(
children: [
Expanded(
child: Container(
height: 100,
decoration: BoxDecoration(color: Colors.red),
),
),
Text('125.00%')
],
),
Row(
children: [
Expanded(
child: Container(
height: 100,
decoration: BoxDecoration(color: Colors.red),
),
),
Text('1250.00%')
],
),
],
);
}

我怎样才能使所有的文本采取相同的水平空间,而不使用像素的宽度,使所有的容器垂直对齐?

我想为我的百分比设置一个固定的长度,较短的百分比用空格填充,较长的百分比用文本省略号裁剪。

是否有一个干净的内置方法来做到这一点?

既然你的要求是设置一个固定的宽度的百分比和椭圆大小的文本,如果它溢出,我建议你包装你的Text小部件也在Expanded小部件和使用flex属性的两个扩展组件的行。我建议行中两个分量的比例为5:1,分别由flex1flex2表示。但是,您可以根据自己的要求设置弹性。其次,我在所有Text小部件中使用了overflow: TextOverflow.ellipsis,这些小部件将处理您的需求中的省略部分。我还将文本向右对齐,但这完全取决于u。

修改后的代码如下:

Widget example2() {
int flex1 = 5;
int flex2 = 1;
return Column(
children: [
Row(
children: [
Expanded(
flex: flex1,
child: Container(
height: 100,
decoration: BoxDecoration(color: Colors.red),
),
),
Expanded(
flex: flex2,
child: const Text('25.00%',
overflow: TextOverflow.ellipsis,
textAlign: TextAlign.right,
),
)
],
),
Row(
children: [
Expanded(
flex: flex1,
child: Container(
height: 100,
decoration: BoxDecoration(color: Colors.red),
),
),
Expanded(
flex: flex2,
child: const Text('125.00%',
overflow: TextOverflow.ellipsis,
textAlign: TextAlign.right,
),
)
],
),
Row(
children: [
Expanded(
flex: flex1,
child: Container(
height: 100,
decoration: BoxDecoration(color: Colors.red),
),
),
Expanded(
flex: flex2,
child: const Text(
'1250.00%',
overflow: TextOverflow.ellipsis,
textAlign: TextAlign.right,
),
)
],
),
],
);
}

希望有帮助!

所有这些问题的解决方案是在auto_size_text包中,你可以设置一个maxLines来设置AutoSizeText的最大行数,所以如果你有多个AutoSizeText小部件,所有的都将占用相同的水平空间,因为你的文本很长,包将调整大小以适应特定的行范围,否则,你可以给它省号样式。

AutoSizeText(
yourText,
maxLines: 1,
minFontSize: 10,
wrapWords: false,
overflow: TextOverflow.ellipsis,
);

最新更新