Search code examples
flutterflutter-layoutflutter-web

Flutter wrapping Row in SingleChildScrollview ruins spaceBetween


I have aRow of buttons which have a parent of SingleChildScrollView, horizontally. After wrapping the SingleChildScrollView the elements of the row don't respect the mainAxisAlignment, specifically spaceBetween, they are together with not space in between...

How can I make the spaceBetween work again?

SingleChildScrollView(
  scrollDirection: Axis.horizontal,
  child: Row(
    mainAxisAlignment: MainAxisAlignment.spaceBetween,
    mainAxisSize: MainAxisSize.max,
    children: const [
      TransportModeButton(
        iconPath: 'images/icons/walking_icon.png',
        text: 'Walking',
      ),
      TransportModeButton(
        iconPath: 'images/icons/bicycle_icon.png',
        text: 'Bike & eScooter',
      ),
      TransportModeButton(
        iconPath: 'images/icons/public_transport_icon.png',
        text: 'Public transport',
      )
    ],
  ),
),

Solution

  • you can solve it by wrapping your Row inside a BoxConstraints like:

    Container(
            child: SingleChildScrollView(
                scrollDirection: Axis.horizontal,
                child: ConstrainedBox(
                  constraints: BoxConstraints(
                    maxWidth: MediaQuery.of(context).size.width,
                  ),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    mainAxisSize: MainAxisSize.max,
                    children: const [
                      Text("test1"),
                      Text("test2"),
                      Text("test3"),
                    ],
                  ),
                )),
          ),
    

    Edit:

    to get the constraints from the parents for your SingleChildsScrollView you can do so using LayoutBuilder, so the code would look like:

    LayoutBuilder(
                    builder: (BuildContext context, BoxConstraints constraints) {
                  return SingleChildScrollView(
                      scrollDirection: Axis.horizontal,
                      child: ConstrainedBox(
                        constraints: BoxConstraints(
                          maxWidth: constraints.maxWidth,
                        ),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          mainAxisSize: MainAxisSize.max,
                          children: const [
                            Text("test1"),
                            Text("test2"),
                            Text("test3"),
                          ],
                        ),
                      ));
                })