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

如何在Flutter的GridView.builder中为每张图片下方添加文本内容?

实现方法

你只需要调整每个网格项的内部布局,再适配网格的宽高比即可,具体修改如下:

  1. 首先给SliverGridDelegateWithFixedCrossAxisCount添加childAspectRatio属性,调整网格单元的宽高比(默认是1:1,加了文本后需要缩小这个值,比如设为0.75,可根据实际文本长度调整)
  2. 把每个Container的子组件从单独的Image.network改成Column垂直布局,从上到下依次放图片、间隔、文本组件即可。

修改后的参考代码

child: GridView.builder(
  primary: false,
  padding: const EdgeInsets.all(20),
  gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
    crossAxisSpacing: 10,
    mainAxisSpacing: 10,
    crossAxisCount: 2,
    // 新增宽高比,数值为宽度/高度,值越小单元高度越高
    childAspectRatio: 0.75,
  ),
  itemCount: 10,
  itemBuilder: (BuildContext context, int index) {
    Widget widget;
    switch (index) {
      case 0:
        widget = Container(
          padding: const EdgeInsets.all(8),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(10),
            color: Colors.white,
          ),
          // 替换为Column垂直布局
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Expanded(
                child: Image.network(
                  'https://ezyorder.com.my/uploads/products/t-shirt_man.png',
                  fit: BoxFit.contain,
                ),
              ),
              // 图片和文本的间隔
              const SizedBox(height: 8),
              const Text(
                "男士T恤",
                style: TextStyle(fontSize: 14),
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
              ),
            ],
          ),
        );
        break;
      case 1:
        widget = Container(
          padding: const EdgeInsets.all(8),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(10),
            color: Colors.white,
          ),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Expanded(
                child: Image.network(
                  'https://ezyorder.com.my/uploads/products/black_full_sleeves.png',
                  fit: BoxFit.contain,
                ),
              ),
              const SizedBox(height: 8),
              const Text(
                "黑色长袖上衣",
                style: TextStyle(fontSize: 14),
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
              ),
            ],
          ),
        );
        break;
      // 其余index的逻辑同理修改即可
      default:
        widget = const SizedBox();
    }
    return widget;
  },
)

补充说明

  • 如果文本需要显示多行,把maxLines改成对应数值即可,同时可以适当调小childAspectRatio的值增加单元高度
  • Image外层加Expanded是为了让图片自适应剩余高度,避免尺寸溢出

内容的提问来源于stack exchange,提问作者Jian Yuan Ng

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 10:24:02