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

Flutter:如何在GridView中定期插入全屏宽度的广告组件

实现GridView每隔10行插入全屏广告横幅的方案

针对你现有crossAxisCount=2的GridView,要实现每隔10行插入占满整行的广告,这里提供两种可行方案:

方案一:原生Flutter实现(无需第三方库)

因为GridView.count不支持单个item跨列占满整行,我们可以改用CustomScrollView,将原列表拆分为每20个item(对应10行)一组,每组用SliverGrid.count渲染,组与组之间插入广告横幅:

CustomScrollView(
  controller: _scrollController,
  physics: const AlwaysScrollableScrollPhysics(),
  slivers: [
    // 遍历原列表,每20个item为一组
    for (int i = 0; i < widgetList.length; i += 20)
      ...[
        SliverGrid.count(
          crossAxisCount: 2,
          childAspectRatio: 1 / 1.05,
          crossAxisSpacing: 0,
          mainAxisSpacing: 5.0,
          // 取当前组的item,避免越界
          children: widgetList.sublist(i, min(i + 20, widgetList.length)),
        ),
        // 非最后一组时插入广告横幅
        if (i + 20 < widgetList.length)
          SliverToBoxAdapter(
            child: Container(
              height: 100, // 根据你的广告需求设置高度
              color: Colors.grey[200],
              alignment: Alignment.center,
              child: const Text("广告横幅"),
            ),
          ),
      ],
  ],
)

逻辑说明:

  • 每20个普通item对应10行(因为每行2列),每组用SliverGrid.count保持原有的布局参数
  • 用SliverToBoxAdapter包裹广告组件,它会自动占满父级宽度,实现全屏横幅效果
  • 保留了你原有的_scrollController、physics等参数,保证滚动行为一致

方案二:使用第三方库简化实现

如果不想拆分列表,可以使用flutter_staggered_grid_view库,它支持单个item设置跨列数:

步骤1:添加依赖

在pubspec.yaml中加入:

dependencies:
  flutter_staggered_grid_view: ^0.7.0

步骤2:替换原GridView为StaggeredGridView

import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';

StaggeredGridView.countBuilder(
  controller: _scrollController,
  scrollDirection: Axis.vertical,
  crossAxisCount: 2,
  crossAxisSpacing: 0,
  mainAxisSpacing: 5.0,
  physics: const AlwaysScrollableScrollPhysics(),
  // 总item数 = 原列表长度 + 广告数量(每20个item插1个广告)
  itemCount: widgetList.length + (widgetList.length ~/ 20),
  itemBuilder: (context, index) {
    // 计算当前索引对应的原列表位置
    final adCount = index ~/ (20 + 1);
    final originalIndex = index - adCount;
    
    if (originalIndex >= widgetList.length) {
      // 广告位置,返回你的广告组件
      return Container(
        height: 100,
        color: Colors.grey[200],
        alignment: Alignment.center,
        child: const Text("广告横幅"),
      );
    } else {
      // 普通item,返回原列表的组件
      return widgetList[originalIndex];
    }
  },
  staggeredTileBuilder: (index) {
    final adCount = index ~/ (20 + 1);
    final originalIndex = index - adCount;
    
    if (originalIndex >= widgetList.length) {
      // 广告占满2列
      return const StaggeredTile.fit(2);
    } else {
      // 普通item占1列
      return const StaggeredTile.fit(1);
    }
  },
)

逻辑说明:

  • 通过staggeredTileBuilder为广告item设置fit(2),让它占满整行
  • 计算索引时自动扣除广告的数量,保证原列表item的顺序正确
  • 完全保留原GridView的布局参数,无需大幅调整代码

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 09:00:50