1

I have a DataTable widget which very occasionally spills off the screen. So I nested it in a SingleChildScrollView, but in most situations, this uglifies the DataTable. The DataTable no longer defaults to filling its parent width, but instead Centers itself in the middle of the screen.

I want it to fill the width of the screen, each column Expanded to fill the space available. With this behaviour only changing if it needs to scroll.

I've tried Googling extensively; existing Sliver-based solutions on StackOverflow haven't worked thus far.

I've tried ConstrainedBox, which meant that instead of Centering the DataTable, it aligned it to the left of the screen. But my fiddling didn't get it to stretch across the screen.

I've tried making SingleChildScrollView a child of an Expanded widget, to no success.

Do I have to forfeit a pretty, screen-spanning table for scrolling functionality?

SingleChildScrollView(scrollDirection: Axis.horizontal, child:
                DataTable(columns: <DataColumn> [
                DataColumn(label: Expanded(child: Text('Item'))),
              if(widget.neighbour.rent) DataColumn(numeric: true, label: Expanded(child: Text('Rent'))),
            DataColumn(numeric: true, label: Expanded(child: Text('Deposit'))),
            ],
            rows: getTablesRows(),
            ));

Thanks Sam.

enter image description here

Sam
  • 1,659
  • 4
  • 23
  • 42

2 Answers2

2

use a Layout Builder together with a SizeBox, like this:

LayoutBuilder(builder: (context, constraints) {
          return SingleChildScrollView(
            scrollDirection: Axis.horizontal,
            child: SizedBox(
                width: constraints.biggest.width,
                child: youDataTable()),
          );
        })
  • Thanks Renato, this also solved the issue, the SizedBox forcing DataCell lines to wrap, it appears to deactivate scrolling but all content is displayed as was my true aim. – Sam Apr 09 '23 at 13:29
1

wrap the Datatablewith a SizedBoxand give it

width: MediaQuery.of(context).size.width

to have it take the full width of the screen.

Amr Essam
  • 76
  • 3
  • Aha! **NICE**, this doesn't quite do what I asked for, it disables horizontal scrolling, forcing longer Strings in the Table's DataCell widgets to wrap to a second line. But the outcome is better than I asked for. AMAZING, thankyou Amr. – Sam Apr 09 '23 at 13:09