flutterlayoutscrollsinglechildscrollview

Flutter space evenly scrollable layout


I have following design:

enter image description here

Code:

body: Container(
  color: Colors.green,
  child: SingleChildScrollView(
    child: const Column(
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: [
        // TEXT
        // TEXT
        // IMAGE
      ],
    ),
  ),
)

It is fine, when the device is smaller, the column is scrollable:

enter image description here

However, when the device is bigger, I would like to achieve following:

enter image description here

Explanation: all three elements are spaced evenly in the layout. First is on the top, last is on the bottom. If there is enough space, there are spaces between the elements. However, if there is no space, the column would become scrollable. Can somebody advise how to solve this?

I have tried mainAxisAlignment: MainAxisAlignment.spaceEvenly,, but that does not work. Even wrapping the parent container with Expanded does not work either. Thank you very much for your help.


Solution

  • You can actually use something from the example of SingleChildScrollView docs:

    LayoutBuilder(
      builder: (context, constraints) => SingleChildScrollView(
        child: ConstrainedBox(
          constraints: BoxConstraints(minHeight: constraints.maxHeight),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Placeholder(fallbackHeight: 200),
              Placeholder(fallbackHeight: 200),
              Placeholder(fallbackHeight: 200),
            ],
          ),
        ),
      ),
    ),
    

    What you are doing here is making the Column have a minimum constraint equal to the available height (the space you have). Thanks to this, there's a free space available in the Column which is used for the MainAxisAlignment.spaceBetween. If the column contents won't fit within that space, the max height constraint is still infinite, so it will nicely expand and the SingleChildScrollView will make the contents scrollable.

    Just be sure to not use this pattern for longer or more complex (in terms of the widget tree) views, as the SingleChildScrollView lays out the whole child widget tree which for more complex trees may get expensive and your frame time may suffer.