Flutter DataTable 将宽度限制为屏幕宽度并换行文本

Flutter DataTable limit width to screen width & wrap text

这是我的数据表:

SizedBox(
  height: 200,
  child: SingleChildScrollView(
    scrollDirection: Axis.vertical,
    child: DataTable(
      columnSpacing: 0,
      columns: const [
        DataColumn(label: Text("Domain")),
        DataColumn(label: Text("Request count")),
      ],
      rows: const [
        DataRow(cells: [
          DataCell(Text("A very long text which causes the right column to be pushed out of the screen")),
          DataCell(Text("12345")),
        ]),
        DataRow(cells: [
          DataCell(Text("It would be the best if this text would be shown in to lines so that there is enough space for the second column")),
          DataCell(Text("678890")),
        ]),
      ],
    ),
  ),
)

例外情况是:

The following assertion was thrown during layout:
A RenderFlex overflowed by 39 pixels on the right.

The relevant error-causing widget was
DataTable

我希望table限制高度,这样你就可以滚动它,但是水平方向的宽度应该是固定的,这样你就不能滚动了。如果内容不适合列,如上面的错误所示,那么文本不应该从屏幕上消失,而是文本应该进入第二行,以便有足够的 space 用于两列屏幕。我已经尝试了很多东西,但我根本无法限制 table 的宽度,因此它只能与父小部件一样宽。

为每个 DataCell child 提供宽度解决问题。

DataCell(
  SizedBox(
    width: x,
    child: Text(
      "A very long text which causes the right column to be pushed out of the screen",
      overflow: TextOverflow.visible,
      softWrap: true,
    ),
  ),
),

要获得响应宽度,您可以在 body 上使用 LayoutBuilder 并使用它的 width: constraints.maxWidth * .5, 获得屏幕的 50% 宽度或 MediaQuery,(确保最小化填充) .