Flutter:如何使高度(或宽度)根据父级动态变化 |带彩色边框的卡片

Flutter: How to make height (or width) change dynamically depending on the parent | Card with colored border

我创建了一张卡片,其高度取决于其内容,因此它的高度未在任何地方定义。现在我想给Card添加一个蓝色左边框,高度调整为Card(他的父级)当前的高度。

因此,当我输入任何固定高度(例如 50)时,蓝色边框如下所示: 身高:50

这是我的代码:

Card(
          margin: EdgeInsets.zero,
          elevation: 0,
          color: Colors.black12,
          shape: const OutlineInputBorder(
            borderRadius: BorderRadius.all(Radius.circular(6)),
            borderSide: BorderSide.none,
          ),
          child: Container(
            width: double.infinity,
            child: Stack(
              children: [
                Padding(
                  padding: const EdgeInsets.all(16.0),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: const [
                      Text("This is random text."),
                      Text("There can be more."),
                      Text("So the height of this Card is never fix."),
                    ],
                  ),
                ),
                Container(
                  height: 50, // This height must match the current height of the Card
                  width: 8,
                  decoration: const BoxDecoration(
                    color: Colors.blue,
                    borderRadius: BorderRadius.only(topLeft: Radius.circular(6), bottomLeft: Radius.circular(6))
                  ),
                )
              ],
            ),
          ),
        )

但我想要一个动态高度,无论内容是否改变,它看起来总是这样: 高度:匹配卡片的当前高度

double.infinity 对我和扩展小部件都没有帮助。

您可以使用 Containerdecoration 作为父级,并使用 ClipRRect 来圆角。需要的话也可以用卡片包裹起来。

Padding(
  padding: const EdgeInsets.all(24.0),
  child: ClipRRect(
    borderRadius: BorderRadius.circular(12),
    child: Container(
      padding: const EdgeInsets.all(16.0),
      decoration: BoxDecoration(
        color: Colors.grey,
        border: Border(
          left: BorderSide(
            color: Colors.blue,
            width: 12,
          ),
        ),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisSize: MainAxisSize.min,
        children: const [
          Text("This is random text."),
          Text("There can be more."),
          Text("So the height of this Card is never fix."),
        ],
      ),
    ),
  )),

一种用更少的代码来做到这一点的方法:

        Container(
          padding: const EdgeInsets.all(10),
          decoration: BoxDecoration(
            // add Card-like elevation
            boxShadow: kElevationToShadow[4],
            gradient: LinearGradient(
              stops: const [0.03, 0.03],
              colors: [
                Colors.blue,
                Colors.grey[900]!,
              ],
            ),
            borderRadius: BorderRadius.circular(3),
          ),
          child: const Text(' Sunt magna irure ut reprehenderit.'),
        ),

如果您使用渐变,您可能希望在文本左侧添加一些填充,因为它可能会进入下一行的“颜色标记”,具体取决于宽度的大小。

结果