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

atr*_*eon 2 flutter

为什么 AspectRatio 放置在 ListView 中时不保留我的宽高比?

意外行为(不保留 ListView 中的纵横比)

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

在此输入图像描述

预期行为(在 ListView 之外工作)

return Container(
  height: 200,
  child: AspectRatio(
    aspectRatio: 1 / 2,
    child: Container(
      color: Colors.red,
    ),
  ),
);
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

Vic*_*ele 6

这是因为“在横轴上,子项需要填充ListView。 ”所以ListView拉伸了Container。

解决方案是将容器包装在中心小部件中,这有助于维护子小部件的大小“以防父小部件对容器应采用的大小有自己的意见”,如下所示:

 Center(
          child: Container(
            height: 200,
            child: AspectRatio(
              aspectRatio: 1 / 2,
              child: Container(
                color: Colors.red,
              ),
            ),
          ),
    )
Run Code Online (Sandbox Code Playgroud)