为什么AspectRatio在ListView中不起作用?

时间:2019-12-24 19:18:32

标签: flutter

为什么将AspectRatio放置在ListView中时不保留我的纵横比?

意想不到的行为(不会在ListView中保留长宽比)

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

enter image description here

预期的行为(在ListView外部运行)

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

enter image description here

1 个答案:

答案 0 :(得分:1)

这是因为“ in the cross axis, the children are required to fill the ListView.”使ListView拉伸了Container。

解决方案是将“容器”包装在“中心”小部件中,这有助于保持子小部件尺寸“ in case the parent widget has its own opinions regarding the size that the Container should take"”,如下所示:

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