You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让Flutter中三张卡片的子Widget(标题、数值、图标)始终对齐?

解决Flutter卡片子Widget对齐问题

要让三张卡片里的标题、数值、图标始终平行对齐,核心是让每个卡片内的三个模块遵循统一的垂直空间规则,避免因内容长度差异打乱布局。你可以按以下方式修改代码:

关键修改点

  • 给标题文本设置固定行数和溢出处理,防止标题换行导致高度不一致
  • 用Expanded配合固定flex值分配垂直空间,替代Spacer(Spacer会根据剩余空间动态分配,容易出现偏移)
  • 统一数值文本和图标的布局约束,确保位置一致

修改后的完整代码

GridView(
  gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
    crossAxisCount: 3,
    childAspectRatio: 0.75,
    crossAxisSpacing: 10,
    mainAxisSpacing: 5,
  ),
  shrinkWrap: true,
  children: [
    _buildDashboardCard(
      context,
      color: const Color(0xFF93C572),
      title: "tenancies".tr(),
      value: "1",
      icon: Assets.images.tenancyExpiring.image(height: 30),
    ),
    _buildDashboardCard(
      context,
      color: const Color(0xFF96DED1),
      title: "currentOccupancyRate".tr(),
      value: "30.77%",
      icon: Assets.images.occupancy.image(height: 20),
    ),
    // 其他卡片...
  ],
);

Widget _buildDashboardCard(BuildContext context, {
  required Color color,
  required String title,
  required String value,
  required Widget icon,
}) {
  return Container(
    decoration: BoxDecoration(
      borderRadius: BorderRadius.circular(15),
      color: color,
    ),
    child: Padding(
      padding: const EdgeInsets.all(20),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          // 标题区:固定行数,避免换行高度变化
          Expanded(
            flex: 2,
            child: Text(
              title,
              textAlign: TextAlign.center,
              maxLines: 2,
              overflow: TextOverflow.ellipsis,
              style: const TextStyle(height: 1.2), // 统一行高
            ),
          ),
          const SizedBox(height: 10),
          // 数值区:固定flex占比,确保垂直位置一致
          Expanded(
            flex: 3,
            child: Center(
              child: Text(
                value,
                style: Theme.of(context).textTheme.titleLarge,
              ),
            ),
          ),
          // 图标区:固定在右下角,用Expanded确保底部位置
          Expanded(
            flex: 2,
            child: Align(
              alignment: Alignment.bottomRight,
              child: icon,
            ),
          ),
        ],
      ),
    ),
  );
}

额外说明

  • maxLines: 2和overflow: TextOverflow.ellipsis保证标题最多两行,超出部分省略,避免不同标题行数导致高度差异
  • 用Expanded的flex参数给三个区域分配固定的空间比例(比如2:3:2),不管内容长短,每个区域的垂直占比都一致
  • 数值区用Center包裹,确保数值始终在区域中央,避免不同长度的数值位置偏移

内容的提问来源于stack exchange,提问作者John Joe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 05:07:15