Flutter开发中如何实现文本内变量与值的冒号精准对齐?
Flutter 实现键值对冒号精准对齐方案
使用\t制表符调整间距的方式不可靠,制表符宽度受字体、字号、字符宽度影响,不同设备展示效果差异极大,必然会出现错位问题,推荐使用布局组件实现对齐,方案如下:
方案1:使用Table组件(推荐)
Table组件支持统一设置列宽,能保证第一列所有标签宽度一致,冒号自然对齐:
Table( // 第一列固定宽度,数值根据最长的标签长度调整即可 columnWidths: const { 0: FixedColumnWidth(120), 1: FlexColumnWidth(), // 第二列占剩余空间 }, children: [ TableRow( children: [ const Text("name", textAlign: TextAlign.end), const Text(" : Yogi A W"), ], ), TableRow( children: [ const Text("company", textAlign: TextAlign.end), const Text(" : PT XXX"), ], ), TableRow( children: [ const Text("company second", textAlign: TextAlign.end), const Text(" : PT XXXX"), ], ), ], )
方案2:Row+固定宽度容器实现
如果只有少量行,也可以每行单独用Row结构实现:
Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Row( children: const [ // 左侧标签固定宽度,右对齐 SizedBox( width: 120, child: Text("name", textAlign: TextAlign.end), ), Text(" : Yogi A W"), ], ), Row( children: const [ SizedBox( width: 120, child: Text("company", textAlign: TextAlign.end), ), Text(" : PT XXX"), ], ), Row( children: const [ SizedBox( width: 120, child: Text("company second", textAlign: TextAlign.end), ), Text(" : PT XXXX"), ], ), ], )
如果不想写死列宽、需要自适应最长标签的宽度,可以用IntrinsicWidth组件包裹整个Column,设置第一列交叉轴对齐为拉伸即可,注意该组件有性能损耗,不适合长列表场景。
内容的提问来源于stack exchange,提问作者yogithesymbian
相关产品推荐
相关产品推荐

