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

如何在Flutter的ListView中每2个类别自动插入广告组件?

如何在ListView的每2个类别组件间插入广告组件?

我希望每2个类别插入一个广告组件。目前我的ListView通过map方法处理类别数据生成子组件,有没有更简洁的方式修改代码来插入AdWidget()?

[更新] AdWidget()是一个广告组件,可替换为任意组件,例如Text("ad widget here");

初始代码:

ListView(
  physics: const BouncingScrollPhysics(),
  children: widget.superCategory.allCategories
    .map((category) =>
       ClassifiedAdCategoryGalleryStrip(category: category))
       .toList(),
)

当前我的代码实现:

final List<Widget> children = widget.superCategory.allCategories
        .map((category) => ClassifiedAdCategoryGalleryStrip(category: category))
        .toList();

    for (int i = 0; i < children.length; i += 2) {
      if (i == 0) continue;
      children.insert(i, Text("AdWidget"));
    }
    return Scaffold(
        appBar: AppBar(
            title:
                Text(i18n_category_gallery.i18n.fill([widget.superCategory]))),
        body: ListView(
          physics: const BouncingScrollPhysics(),
          children: children,
        ));

更简洁的实现方式

可以直接在遍历生成组件的过程中插入广告,避免后续的列表插入操作,代码更紧凑:

方法一:使用expand方法

return Scaffold(
  appBar: AppBar(
    title: Text(i18n_category_gallery.i18n.fill([widget.superCategory])),
  ),
  body: ListView(
    physics: const BouncingScrollPhysics(),
    children: widget.superCategory.allCategories
        .asMap()
        .expand((index, category) {
          final widgets = [ClassifiedAdCategoryGalleryStrip(category: category)];
          // 每2个组件后插入广告(索引从0开始,第2、4...个组件后添加)
          if ((index + 1) % 2 == 0 && index != widget.superCategory.allCategories.length - 1) {
            widgets.add(const Text("AdWidget")); // 替换为你的AdWidget()
          }
          return widgets;
        })
        .toList(),
  ),
);

方法二:使用fold方法

return Scaffold(
  appBar: AppBar(
    title: Text(i18n_category_gallery.i18n.fill([widget.superCategory])),
  ),
  body: ListView(
    physics: const BouncingScrollPhysics(),
    children: widget.superCategory.allCategories.fold<List<Widget>>([], (list, category) {
      list.add(ClassifiedAdCategoryGalleryStrip(category: category));
      // 当添加的是第2、4...个组件,且不是最后一个时插入广告
      if (list.length % 2 == 0 && list.length != widget.superCategory.allCategories.length * 2 - 1) {
        list.add(const Text("AdWidget"));
      }
      return list;
    }),
  ),
);

注意点

  • 两种方式都不需要提前生成完整的组件列表再循环插入,而是在构建列表时直接处理广告逻辑,代码更简洁易读。
  • 加入index != ...length -1的判断是为了避免在最后一个类别组件之后插入多余的广告。

内容的提问来源于stack exchange,提问作者Stéphane de Luca

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 08:23:20