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

Flutter ListView.builder中如何用if else交替加载两种自定义组件

问题解答

该需求完全可以实现,核心通过ListView.builder回调的index参数做奇偶判断即可实现交替加载两种组件的效果。

注意需要先对齐计数逻辑:Flutter 中itemBuilder的index默认从0开始计数:

  • 若你说的「单数项」是用户视觉上的第1、3、5...项,对应index为偶数
  • 若你说的「单数项」是index本身为奇数的项,调整下方判断条件即可

修改后的完整代码如下:

child: FutureBuilder<Kategori>(
          future: _futureArticles,
          builder: (BuildContext context, AsyncSnapshot<Kategori> snapshot) {
            if (snapshot.hasData) {
              final articles = snapshot.data?.data;

              return ListView.builder(
                  itemCount: articles!.length,
                  itemBuilder: (BuildContext context, int index) {
                    // 视觉单数项(index偶数)用第一种组件,双数项用第二种
                    if (index % 2 == 0) {
                      return customListTile(articles, index, context);
                    } else {
                      return customListTile2(articles, index, context);
                    }
                  });
            }
            // 补全加载状态的占位逻辑,可按需修改
            return const Center(child: CircularProgressIndicator());
          }
),

如果需要调整两种组件的加载顺序,只需将判断条件改为index % 2 == 1即可。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 21:15:02