Flutter DataTable-如何设置列宽



我在Flutter应用程序中使用DataTable。这是我的代码的一个简单示例:

DataTable(
columns: [
DataColumn(label: Text('Column1')),
DataColumn(label: Text('Column2')),
DataColumn(label: Text('Column3')),
],
rows: [
DataRow(cells: [
DataCell(Text('1')),
DataCell(Text('2')),
DataCell(Text('6')),
]),
DataRow(cells: [
DataCell(Text('12')),
DataCell(Text('John')),
DataCell(Text('9')),
]),

],
)

我需要:

-列1为可用宽度的20%

-列1为可用宽度的40%

-列1为可用宽度的40%

我该怎么做?DataTable有可能吗?

您可以尝试以下操作:

import 'package:flutter/material.dart';
void main() {
runApp(MaterialApp(home: MyApp()));
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
final double width = MediaQuery.of(context).size.width;
return Scaffold(
appBar: AppBar(
title: const Text("Flutter Demo"),
),
body: Container(
width: width,
child: DataTable(
columnSpacing: 0,
horizontalMargin: 0,
columns: [
DataColumn(
label: Container(
width: width * .2,
child: Text('Column1'),
),
),
DataColumn(
label: Container(
width: width * .4,
child: Text('Column2'),
),
),
DataColumn(
label: Container(
width: width * .4,
child: Text('Column3'),
),
),
],
rows: [
DataRow(cells: [
DataCell(Text('1')),
DataCell(Text('2')),
DataCell(Text('6')),
]),
DataRow(cells: [
DataCell(Text('12')),
DataCell(Text('John')),
DataCell(Text('9')),
]),
],
),
),
);
}
}

通过上述方法,可以使用MediaQuery计算列大小,但大多数情况下DataTable没有全屏宽度,因此我们无法计算。

您可以使用此软件包来设置各个列宽
https://pub.dev/packages/data_table_2

DataColumn2(
label: Text('#'),
size: ColumnSize.S, // Small column
),

列有预定义的大小,如ColumnSize.M表示中等,ColumnSize.L表示大。如果要修改默认值,则可以使用smRatiolmRatio来调整宽度。

最新更新