有人知道如何在 Flutter 的 DataTable 中动态添加更多行吗?如您所见,我的代码非常“硬编码”[行:11-31]。
应该有一种方法可以摆脱编写越来越多的数据行。
代码:
class DataTableWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
return DataTable(
columns: [
DataColumn(label: Text('Patch')),
DataColumn(label: Text('Version')),
DataColumn(label: Text('Ready')),
],
rows: <DataRow>[
DataRow(
cells: <DataCell>[
DataCell(Text('AAAAAA')),
DataCell(Text('1')),
DataCell(Text('Yes')),
],
),
DataRow(
cells: <DataCell>[
DataCell(Text('BBBBBB')),
DataCell(Text('2')),
DataCell(Text('No')),
],
),
DataRow(
cells: <DataCell>[
DataCell(Text('CCCCCC')),
DataCell(Text('3')),
DataCell(Text('Yes')),
],
),
],
);
}
}
最佳答案
你可以使用
listOfColumns.map(((element) => DataRow(...))).toList()
这是您使用此方法的代码。
class DataTableWidget extends StatelessWidget {
final List<Map<String, String>> listOfColumns = [
{"Name": "AAAAAA", "Number": "1", "State": "Yes"},
{"Name": "BBBBBB", "Number": "2", "State": "no"},
{"Name": "CCCCCC", "Number": "3", "State": "Yes"}
];
// DataTableWidget(this.listOfColumns); // Getting the data from outside, on initialization
@override
Widget build(BuildContext context) {
return DataTable(
columns: [
DataColumn(label: Text('Patch')),
DataColumn(label: Text('Version')),
DataColumn(label: Text('Ready')),
],
rows:
listOfColumns // Loops through dataColumnText, each iteration assigning the value to element
.map(
((element) => DataRow(
cells: <DataCell>[
DataCell(Text(element["Name"])), //Extracting from Map element the value
DataCell(Text(element["Number"])),
DataCell(Text(element["State"])),
],
)),
)
.toList(),
);
}
}
关于dart - 如何在 flutter 中动态添加项目到表中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53997496/