skip to Main Content

I’m a newbie to Flutter, and I found a wired problem when I put a Container into a Column, the Container will be expanded horizontally to fill the whole row. The only way to keep it the original size is by inserting a row between the column and the container. Below is my code. Appreciate for any help

expanded version:

  Widget _concernButton({required BuildContext context, required Dog? dog}) {
final theme = Theme.of(context);
return InkWell(
    onTap: null,
    child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 10),
        alignment: Alignment.center,
        decoration: const BoxDecoration(
          color: Colors.orange,
          borderRadius: BorderRadius.all(Radius.circular(10)),
        ),
        child: Text("标记", style: theme.textTheme.labelLarge)));
}


Widget _content({required BuildContext context, required Dog? dog}) {
    return Column(
      children: [
        _concernButton(context: context, dog: dog)
      ],
    );
}

expanded version UI:
enter image description here

normal version:

  Widget _concernButton({required BuildContext context, required Dog? dog}) {
final theme = Theme.of(context);
return InkWell(
    onTap: null,
    child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 10),
        alignment: Alignment.center,
        decoration: const BoxDecoration(
          color: Colors.orange,
          borderRadius: BorderRadius.all(Radius.circular(10)),
        ),
        child: Text("标记", style: theme.textTheme.labelLarge)));
 }

  Widget _content({required BuildContext context, required Dog? dog}) {
    return Column(
      children: [
        Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [_concernButton(context: context, dog: dog)])
      ],
    );
  }

normal version UI:enter image description here

2

Answers


  1. Did you try wrapping the container in flexible?

    Flexible can be used to space children inside a column,row or flex to fill the space in proportions of the flex factor. Flexible widget allows its child to maintain it’s original size.

    Expanded on the other hand forces the child to automatically use up all the remaining space.

    Try:

    return Column(
      children: [
        Flexible(
         child: _concernButton(context: context, dog: dog),
        )
      ],
    );
    

    If it doesn’t work too, try adding width constraints on the container widget.

    Login or Signup to reply.
  2. This happens because of the alignment: Alignment.center property on your Container. This causes the Container to expand to take up all available space, and put it’s child in the center.

    If you need centering the widget, then wrap your Container in a Center widget instead.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search