2

Why does AspectRatio not preserve my aspect ratio when it is placed in a ListView?

Unexpected behaviour (doesn't preserve aspect ratio in a ListView)

return ListView(
  children: [
    Container(
      height: 200,
      child: AspectRatio(
        aspectRatio: 1 / 2,
        child: Container(
          color: Colors.red,
        ),
      ),
    ),
  ],
);

enter image description here

Expected behaviour (works outside of a ListView)

return Container(
  height: 200,
  child: AspectRatio(
    aspectRatio: 1 / 2,
    child: Container(
      color: Colors.red,
    ),
  ),
);

enter image description here

1 Answer 1

6

This is because "in the cross axis, the children are required to fill the ListView." So the ListView stretches the Container.

The solution will be to wrap the Container in a Center widget which helps maintain the child widget size "in case the parent widget has its own opinions regarding the size that the Container should take" like below:

 Center(
          child: Container(
            height: 200,
            child: AspectRatio(
              aspectRatio: 1 / 2,
              child: Container(
                color: Colors.red,
              ),
            ),
          ),
    )
1
  • 1
    That is great, I thought AspectRatio should have overridden the value but that works. Great answer :-)
    – atreeon
    Dec 26, 2019 at 13:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.