Flutter DataTable 如何限制宽度为屏幕宽度并换行文本?

3
这是我的数据表格:
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

我希望表格的高度受限,这样你就可以通过滚动来查看它,但是水平方向的宽度应该是固定的,这样你就无法滚动。如果内容不能适应列中,就像上面的错误显示的那样,那么文本不应该从屏幕上消失,而是应该进入第二行,这样屏幕上就有足够的空间容纳两列。我已经尝试了很多方法,但我无法将表格的宽度限制为与父部件一样宽。


文字被截断或换行,我对这部分感到困惑。 - Yeasin Sheikh
目前,右侧简单地截断了第二列。相反,一列或两列的文本应该延伸到第二行,以便两列并排放置。 - PlutoHDDev
你能提供一个简单的代码片段吗?但是如果它包含了缺失引用的额外代码,比如“snapshot”,该怎么办? - Yeasin Sheikh
我已经用一个更简单的代码片段替换了原来的代码。 - PlutoHDDev
2个回答

3
为每个子元素提供宽度可以解决这个问题。
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(确保最小化填充)。

1
我现在正在使用LayoutBuilder包装DataTable并尝试width: constraints.maxWidth * .8width: constraints.maxWidth * .2。 我不知道为什么它不能完全正常工作,我必须使用(constraints.maxWidth - 50) * factor,否则右侧列仍然被裁剪。 你有任何想法吗?我已经直接将LayoutBuilder包装在DataTable周围,并设置columnSpacing: 0,这里我没有使用任何填充。 - PlutoHDDev
1
可能是问题装饰,它具有填充或类似于您通过最小化50px解决的占用一些空间的东西。 - Yeasin Sheikh
1
我刚发现我还需要设置horizontalMargin: 0,然后我就不需要再减去50像素了。 - PlutoHDDev

0

DataTable 小部件用 FittedBox 包装解决了所有问题!


1
你可以提供一个解决方案的例子,并说明它如何帮助问题的提出者,从而改进你的回答。 - Tyler2P

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接