flutter DataTable多行缠绕和居中



我正在尝试在flutter中的DataTable((的DataColumn((行中有多条居中的行。不过,似乎不支持居中或多行。

我的DataTable代码看起来像这样:

class TestDayData extends StatelessWidget {
final List<String> timesList = [
"This is",
"a bunch",
"of strings",
];
final String day;
TestDayData({Key key, this.day}) : super(key: key);
@override
Widget build(BuildContext context) {
return Container(
child: DataTable(
showCheckboxColumn: false,
columns: [
DataColumn(
label: Center(child: Text(day)),
numeric: false,
),
],
rows: timesList
.map(
(times) => DataRow(cells: [
DataCell(
Text(times.toString()),
),
]),
)
.toList(),
),
);
}
}

我在这里制作了一个dartpad文件,在更大的上下文中显示上面的代码。(我之所以将多个DataTable放在一个Row小部件中,而不是整天使用一个DataTable,是因为我计划将每个DataTable放进一个Stack小部件,这样我就可以将约会覆盖在列的顶部。(

https://dartpad.dev/44bbb788e0d5f1e6393dd38a29430981

到目前为止,我可以通过添加空格和使用换行符来近似一个多行、居中的DataColumn行,如dartpad文件中所示。(但必须有更好的方法!(

Text小部件中缺少textAlign属性

DataTable(
showCheckboxColumn: false,
columns: [
DataColumn(
label: Center(child: Text(day, textAlign:TextAlign.center)),
numeric: false,
),
],
rows: timesList
.map((times) => DataRow(cells: [
DataCell(
Text(times.toString(), textAlign: TextAlign.center),
),
]),
)
.toList(),
),

对我来说,在DataColumn上使用Center小部件或Text小部件上的textAlign属性不起作用:

这是我的解决方案:

DataColumn(
label: Expanded(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: const [Text("text")],
),
),
),

DataCellCenter小部件配合得很好

您可以尝试将文本集中在Datacolumn 中

DataColumn(
label: Center( widthFactor: 1.4,
child: Text("HELLO", textAlign: TextAlign.center,
style: TextStyle(fontSize: 18.0,),),)),

您可以尝试将文本集中在数据单元格中的行中。

DataCell( Center(child: Text("Hello")))

我找到了解决方案。

您只需要使用Center小部件包装文本,然后使用Expanded小部件再次包装文本,如下所示:

DataTable(
columns: [
DataColumn(label: Expanded(child: Center(child: Text('ID', textAlign: TextAlign.center,))),),
DataColumn(label: Expanded(child: Center(child: Text('name', textAlign: TextAlign.center,)))),
]
)

这是集中的最佳方式:

Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Expanded(
child: PaginatedDataTable(
source: data,
header: const Center(child: Text('My Products')),
columns: const [
DataColumn(label: Text('ID')),
DataColumn(label: Text('Name')),
DataColumn(label: Text('Price'))
],
columnSpacing: 100,
horizontalMargin: 10,
rowsPerPage: 8,
showCheckboxColumn: false,
),
),
],
),