Home > Mobile >  Flutter: child button filling container size with explicit size
Flutter: child button filling container size with explicit size

Time:10-15

I'm trying to have a button nested in a container with a specific background color. I'm setting the height on the Container and on the MaterialButton nested within. I would expect the MaterialButton to maintain it's height of 40, while in the container of height 100. Instead, the MaterialButton is stretch to the height and width of the container.enter image description here

Container(
                    color: lightBackground,
                    height: 100,
                    width: double.infinity,
                    child: MaterialButton(
                      height: 40,
                      child: Text('Hi'),
                      color: primaryColor,
                      onPressed: () {},
                    ))

Anyone know how to get round this? Thanks.

CodePudding user response:

The simple solution is to set alignment: Alignment.center for the Container, or wrap the Button with a Center widget.

For example:

Container(
   height: 100,
   alignment: Alignment.center,
   child: ...
)

The long explanation has to do with Flutter Layout Constraints. You can read more about it at the official doc here.

  • Related