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

Flutter使用PageView.builder插入广告页后页码跳页缺失如何解决

问题根源

  • 当前逻辑直接把PageView的滚动下标当成了内容页的页码,只有奇数下标才会展示内容页,自然会出现页码1、3、5跳着展示的问题
  • 内容列表取数逻辑错误,不管当前下标对应广告还是内容,都直接用immunityBoosterworkoutlist[index]取值,会导致内容下标占用错位
  • 原计算逻辑的首屏下标为0,刚好命中偶数判定返回广告页,不符合正常内容优先的展示逻辑

解决方案

如果需要实现「内容页→广告页→内容页」的穿插顺序,30个内容页全部按升序展示不遗漏,按以下逻辑修改即可:

  1. 总页数计算:30个内容 + 29个间隔广告,总页数为 30*2 -1 = 59
  2. 下标映射逻辑:偶数下标对应内容页,奇数下标对应广告页,内容页的真实下标为 PageView下标 / 2 向下取整
  3. 仅在内容页场景下取内容列表的对应数据

修改后的代码如下:

body: PageView.builder(
          controller: _pageController,
          // 总页数=内容数*2 -1,对应30个内容+29个间隔广告
          itemCount: 30 * 2 - 1,
          itemBuilder: (BuildContext context, int index) {
            // 偶数下标为内容页
            if (index % 2 == 0) {
              // 计算内容真实下标
              int contentIndex = index ~/ 2;
              final workoutindex = immunityBoosterworkoutlist[contentIndex];
              return Container(
                child: Center(child: Text('page ${contentIndex + 1}')),
              );
            } 
            // 奇数下标为广告页
            else {
              return Container(
                child: Center(child: Text('Ads Page')),
              );
            }
} 

如果业务需要首屏先展示广告,再按「广告→内容页→广告→内容页」的顺序展示,只需调整总页数和下标映射逻辑即可:

  1. 总页数为 30*2 = 60
  2. 奇数下标对应内容页,内容真实下标为 (PageView下标 -1) ~/ 2
    对应代码:
body: PageView.builder(
          controller: _pageController,
          itemCount: 30 * 2,
          itemBuilder: (BuildContext context, int index) {
            if (index % 2 == 0) {
              return Container(
                child: Center(child: Text('Ads Page')),
              );
            } else {
              int contentIndex = (index - 1) ~/ 2;
              final workoutindex = immunityBoosterworkoutlist[contentIndex];
              return Container(
                child: Center(child: Text('page ${contentIndex + 1}')),
              );
            }
} 

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 04:54:04