fluttersinglechildscrollview

In Flutter how to make SingleChildScrollView scroll horizontally as well as vertically with fixed height


I am creating an App that will have multiple tables on the same page. I want these tables to have a MaxHeight of say 200 and the table should be able to scroll both-ways, i,e. horizontally as well as vertically. I tried to nest SingleChildScrollView within another SingleChildScrollView which doesn't work. Here is code:

return Card(
  color: const Color.fromARGB(0, 183, 183, 202),
  child: Padding(
    padding: const EdgeInsets.all(16.0),
    child: SingleChildScrollView(
      scrollDirection: Axis.vertical,          
      child: SingleChildScrollView(
        scrollDirection: Axis.horizontal,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              widget.dataScreenTitle,
              style: Theme.of(context).textTheme.titleLarge,
            ),
            const SizedBox(height: 8.0),
            DataTable(
              columns: columnTitles,
              rows: dataRows,
            ),
          ],
        ),
      ),
    ),
  ),
);

And there is no way to specify the height.


Solution

  • One way to achieve what you require is to use a ConstrainedBox widget along with a single SingleChildScrollView.

    return Card(
      color: const Color.fromARGB(0, 183, 183, 202),
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: ConstrainedBox(
          constraints: BoxConstraints(maxHeight: 200), // Set maxHeight here
          child: SingleChildScrollView(
            scrollDirection: Axis.vertical,
            child: SingleChildScrollView(
              scrollDirection: Axis.horizontal,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    widget.dataScreenTitle,
                    style: Theme.of(context).textTheme.titleLarge,
                  ),
                  const SizedBox(height: 8.0),
                  DataTable(
                    columns: columnTitles,
                    rows: dataRows,
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
    );
    

    DARTPAD DEMO