IntrinsicHeight 使用详解

916 阅读1分钟

IntrinsicHeight 是一个小部件,它可以根据其子元素的大小来确定自身的高度。它对于需要将多个子元素视为相同高度的情况非常有用

以下是使用 IntrinsicHeight 将三个子元素的高度统一的示例代码:

 IntrinsicHeight(
  child: Row(
    crossAxisAlignment: CrossAxisAlignment.start,
    mainAxisSize: MainAxisSize.min,
    children: [
      appText(
        title,
        12.px,
        AppColor.contentText,
        bold: true,
      ),
      16.spaceWidth,
      Expanded(
        child: appText(
          content,
          12.px,
          AppColor.descriptionText,
          maxLines: null,
          textAlign: TextAlign.left,
        ),
      ),
      Align(
        alignment: Alignment.bottomRight,
        child: Text.rich(
          TextSpan(
            children: [
              const TextSpan(
                text: '¥',
                style: TextStyle(
                  color: Color(0xFFF17051),
                  fontSize: 12,
                  fontFamily: 'PingFang SC',
                  fontWeight: FontWeight.w600,
                  height: 1.17,
                ),
              ),
              TextSpan(
                text: coursePrice ?? '',
                style: const TextStyle(
                  color: Color(0xFFF17051),
                  fontSize: 24,
                  fontFamily: 'DIN-Bold',
                  fontWeight: FontWeight.w700,
                  height: 0.58,
                ),
              ),
              const TextSpan(
                text: '/课时',
                style: TextStyle(
                  color: Color(0xFFF17051),
                  fontSize: 12,
                  fontFamily: 'PingFang SC',
                  fontWeight: FontWeight.w400,
                  height: 1.17,
                ),
              ),
            ],
          ),
        ),
      ),
    ],
  ),
),

如图

image.png

使用 IntrinsicHeight 来包裹 Row,以确保三个子元素具有相同的高度。然后,我们设置 RowcrossAxisAlignmentCrossAxisAlignment.start,使子元素在垂直方向上拉伸以填充整个高度。

每个子元素都被包裹在一个 Flexible 小部件中,以便它们可以根据需要拉伸或收缩。您可以替换 YourFirstWidget()YourSecondWidget()YourLastWidget() 为您实际使用的小部件。

这样,使用 IntrinsicHeightFlexible,您可以确保三个子元素具有相同的高度,并且不会受到父元素宽度或其他因素的影响。