Flutter中使用Row与Column动态生成图表图例的文本对齐问题
你的实现问题在于,每个图例行都是独立的Row组件,单个Row内的元素宽度由自身内容决定,不同行同位置的元素宽度不统一,自然会出现错位。可以用两种方案解决:
方案1:使用Table组件(最推荐)
Table天生支持行列对齐,不用手动计算各列宽度,适配性更好,修改后代码如下:
Widget _buildLegends() { return Table( // 可根据需求调整各列宽度分配,也可以省略让Table自动适配 columnWidths: const { 0: FlexColumnWidth(2), // 第一列(说明文本)占2份宽度 1: FixedColumnWidth(50), // 第二列(色块)固定宽度50 2: FlexColumnWidth(2), // 第三列(指标名)占2份宽度 3: FlexColumnWidth(1), // 第四列(数值)占1份宽度 }, defaultVerticalAlignment: TableCellVerticalAlignment.middle, children: List.generate(sectionDataList.length, (index) { return TableRow( children: [ Padding( padding: const EdgeInsets.all(8.0), child: Text( indicatorDataList[index].subText, textAlign: TextAlign.left, ), ), Padding( padding: const EdgeInsets.all(8.0), child: Container( height: 25, width: 50, color: indicatorDataList[index].color, ), ), Padding( padding: const EdgeInsets.all(8.0), child: Text(indicatorDataList[index].text), ), Padding( padding: const EdgeInsets.all(8.0), child: Text(indicatorDataList[index].value.toString()), ), ], ); }), ); }
方案2:保留Column+Row结构,强制统一列宽
如果不想更换组件,可以给Row内每个位置的子组件套上Expanded或者固定宽度的SizedBox,保证所有行同列的宽度一致:
Widget _buildLegends() { return Column( children: List.generate(sectionDataList.length, (index) { return Padding( padding: const EdgeInsets.all(8.0), child: Row( crossAxisAlignment: CrossAxisAlignment.center, children: [ Expanded( flex: 2, child: Text( indicatorDataList[index].subText, textAlign: TextAlign.left, ), ), SizedBox( width: 50, child: Container( height: 25, color: indicatorDataList[index].color, ), ), Expanded( flex: 2, child: Text(indicatorDataList[index].text), ), Expanded( flex: 1, child: Text( indicatorDataList[index].value.toString(), ), ), ], ), ); }), ); }
内容的提问来源于stack exchange,提问作者Hunt
相关产品推荐
相关产品推荐

