atreeon
atreeon

Reputation: 24167

Why does AspectRatio not work in a ListView?

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

Upvotes: 2

Views: 2407

Answers (1)

Victor Eronmosele
Victor Eronmosele

Reputation: 7716

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,
              ),
            ),
          ),
    )

Upvotes: 6

Related Questions