Flutter - 如何垂直扩展容器?

Flutter - how to expand container vertically?

我有一行包含图像和一列。但是当图像拉伸父容器时,蓝色容器不会拉伸。我认为 Container 默认会拉伸。这背后的原因是什么?

Image

Container(
  color: Colors.purple,
  child: Row(
    children: [
      Flexible(
        child: AspectRatio(
          aspectRatio: 4 / 3,
          child: Image.asset(
            'assets/images/image.jpg',
            fit: BoxFit.cover,
          ),
        ),
      ),
      Flexible(
        child: Container(
          color: Colors.blueAccent,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [Text('data'), Text('data')],
          ),
        ),
      )
    ],
  ),
);

容器的大小由多种因素决定,包括父约束是否有界,是否有子约束等。容器不会“默认拉伸”。

对于您的情况,最简单的解决方案是在您的 Row 小部件上设置 crossAxisAlignment: CrossAxisAlignment.stretch,然后用 IntrinsicHeight 小部件包装它。

修改您的代码:

Container(
  color: Colors.purple,
  child: IntrinsicHeight( // <--- add this
    child: Row(
      crossAxisAlignment: CrossAxisAlignment.stretch, // <-- add this
      children: [
        ...