首页 > 解决方案 > Flutter DataTable - 如何制作具有不同数量数据单元的表格(使某些数据单元跨越多列)

问题描述

我打算输出一个有 2 行的表,第一行包含 3 列,第二行只包含一个,这意味着第二行中的单元格应该跨越 3 列。

这是我的代码:

 DataTable(
      columns: [
        DataColumn(label: Text('#')),
        DataColumn(label: Text('Name')),
        DataColumn(label: Text('Price')),
      ],
      rows: [
        DataRow(cells: [
          DataCell(Text('1')),
          DataCell(Text(orderItem.title)),
          DataCell(Text(orderItem.price.toString())),
        ]),
        DataRow(cells: [
          DataCell('Total: ${orderItem.price}'),
        ]),
      ],
)

由于第二行只有 1 个数据单元,这是我得到的错误:

'package:flutter/src/material/data_table.dart': Failed assertion: line 480 pos 15: '!rows.any((DataRow row) => row.cells.length != columns.length)': is not true.

如何使第二行单元格跨越 3 列?

标签: flutter

解决方案


可悲的是,不支持跨越。我通常要么添加空单元格(如果您不需要空间),或者,如果您确实需要使用您的内容跨越多个单元格,则在单元格中Column添加带有小部件的单列表格(或只是一个)Row

 DataTable(
      columns: [
        DataColumn(label: Text('#')),
        DataColumn(label: Text('Name')),
        DataColumn(label: Text('Price')),
      ],
      rows: [
        DataRow(cells: [
          DataCell(Text('1')),
          DataCell(Text(orderItem.title)),
          DataCell(Text(orderItem.price.toString())),
        ]),
        DataRow(cells: [
          DataCell(Text('Total: ${orderItem.price}')),
          DataCell(SizedBox.shrink()),
          DataCell(SizedBox.shrink()),
        ]),
      ],
)

推荐阅读