Joe Lapp
Joe Lapp

Reputation: 2965

Keep widget from filling ancestor Expanded in Flutter

How do I keep a RaisedButton from expanding to fill an Expanded that contains it? I want to create three columns of widths proportional to the space available, but I want the child in each column to be its natural size, without consuming the entire width of its parent Expanded.

  Widget _controls(BuildContext cx) {
    return Row(
      children: [
        Expanded(
          flex: 1,
          child: player.isOnFirstItem
              ? Container()
              : IconButton(
                  icon: Icon(Icons.arrow_back),
                  onPressed: () => control.gotoPreviousItem(),
                ),
        ),
        Expanded(
          flex: 4,
          child: player.isComplete()
              ? Text(player.currentItem.status) // I'll be adding more here
              : RaisedButton(
                  child: Text(player.currentItem.actionText),
                  onPressed: () => player.currentItem.action(),
                ),
        ),
        Expanded(
          flex: 1,
          child: player.isOnLastItem
              ? Container()
              : IconButton(
                  icon: Icon(Icons.arrow_forward),
                  onPressed: () => player.gotoNextItem(),
                ),
        ),
      ],
    );

The RaisedButton also fills the flex space when I further nest it within a Container. I can't figure out which properties might prevent this.

Searching around for answers, it seems that everyone is trying to accomplish just the opposite.

Upvotes: 10

Views: 3452

Answers (1)

Pablo Barrera
Pablo Barrera

Reputation: 10963

Look what the documentation of Expanded says:

A widget that expands a child of a Row, Column, or Flex so that the child fills the available space.

So, the RaisedButton will fill the available space.

You tried to wrap the button with Container, but look what the documentation of Container says in case it has a child:

(in that case) the widget has a child but no height, no width, no constraints, and no alignment, and the Container passes the constraints from the parent to the child and sizes itself to match the child.

So, the RaisedButton will take the constraints from the parent of the Container, which is to fill the available space.

What you need is to wrap the RaisedButton with a widget that doesn't size itself to match the child's size (because it won't expand) and doesn't alter the size of the child (because the child could expand).

So, some widgets to wrap the RaisedButton that meets these conditions could be:

  • Row
  • Wrap
  • UnconstrainedBox
  • Column with mainAxisSize: MainAxisSize.min
  • Center with heightFactor: 1.0.
  • Align with heightFactor: 1.0.

Upvotes: 11

Related Questions