我在我的Flutter应用程序中有一个DataTable。问题是,当数据被填充时,列的宽度会自动设置并且太大了。我该如何手动设置列宽?我尝试在“Widget build”中更改宽度参数,但这会改变整个表格的宽度,而不是所需的列。
为 DataTable
添加 columnSpacing
属性。默认设置为 56.0。
columnSpacing: 30.0
@Smith,你的意思是你不能做这个吗?如果你能分享一些代码...
Widget build(BuildContext context) {
return Scaffold(
body: DataTable(
columns: [DataColumn(label: Text('label'))],
rows: [
DataRow(cells: [DataCell(
Container(
width: 200, //SET width
child: Text('text')))
])
]
),
);
columnSpacing: 0,
Container
,更好的做法是使用 ConstrainedBox
,这样只有在内容等于或超过约束宽度时单元格大小才会增加。import 'package:flutter/material.dart';
void main() async {
runApp(
MaterialApp(
home: Scaffold(
body: Card(
child: DataTable(columns: [
DataColumn(
label: Text(
'short text column'.toUpperCase(),
style: TextStyle(fontWeight: FontWeight.bold),
)),
DataColumn(
label: Text(
'long text column'.toUpperCase(),
style: TextStyle(fontWeight: FontWeight.bold),
)),
], rows: [
DataRow(cells: [
DataCell(Text('short text')),
DataCell(ConstrainedBox(
constraints: BoxConstraints(maxWidth: 250), //SET max width
child: Text('very long text blah blah blah blah blah blah',
overflow: TextOverflow.ellipsis))),
]),
DataRow(cells: [
DataCell(Text('short text')),
DataCell(ConstrainedBox(
constraints: BoxConstraints(maxWidth: 250), //SET max width
child: Text('very long text blah blah blah blah blah blah',
overflow: TextOverflow.ellipsis))),
])
]),
),
),
),
);
}
return Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
LayoutBuilder(builder: (context, constraints) {
return PaginatedDataTable(
rowsPerPage: 5,
source: dataSource,
showFirstLastButtons: true,
columnSpacing: 50,
horizontalMargin: 0,
columns: [
DataColumn(
label: SizedBox(
// 130 is the amount of space consumed by horizontal Paddings and Margins
width: (constraints.maxWidth - 130) * 0.9,
child: const Padding(
padding: EdgeInsets.fromLTRB(15, 8, 8, 8),
child: Text('Username'),
))),
DataColumn(
label: SizedBox(
width: (constraints.maxWidth - 130) * 0.1,
child: const Padding(
padding: EdgeInsets.fromLTRB(15, 8, 8, 8),
child: Text('Actions'),
)))
],
);
})
]);