flutterdatatablesinglechildscrollview

How to make the child of a SingleChildScrollView full width


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


Solution

  • wrap the Datatablewith a SizedBoxand give it

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

    to have it take the full width of the screen.