Flutter DataTable limit width to screen width & wrap text

5.7k Views Asked by At

This is my DataTable:

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 exception is:

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

The relevant error-causing widget was
DataTable

I want the table to be limited in height, so that you can scroll through it, but horizontally the width should be fixed, so that you cannot scroll. If the content does not fit into the columns, as the above error shows, then the text should not disappear from the screen, but instead the text should go into a second row so that there is enough space for both columns on the screen. I have already tried many things, but I simply cannot limit the width of the table so that it is only as wide as the parent widget.

2

There are 2 best solutions below

3
On BEST ANSWER

Providing width for every DataCell child solve the issue.

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,
    ),
  ),
),

To get responsive width, you can use LayoutBuilder on body and use it's width: constraints.maxWidth * .5, to get 50% width of the screen or MediaQuery, (make sure minimizing the padding).

1
On

Wrapping DataTable widget with FittedBox solved all!