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

Flutter如何在ListView请求加载更多数据时末尾显示CircularProgressIndicator

实现方案

你仅需要修改AdvertisementTileState类的两处代码即可完成需求:

第一步:修改ListView的渲染逻辑

给列表新增一个底部占位位,用来展示加载指示器,修改build方法中的ListView.separated配置:

@override
Widget build(BuildContext context) {
  return NotificationListener(
    onNotification: onNotification,
    child: Padding(
      padding: const EdgeInsets.only(bottom: 28.0),
      child: ListView.separated(
        padding: EdgeInsets.zero,
        scrollDirection: Axis.vertical,
        controller: scrollController,
        // 新增1个位置用来放加载指示器
        itemCount: advertisements.length + 1,
        physics: const AlwaysScrollableScrollPhysics(),
        itemBuilder: (_, index) {
          // 最后一位显示加载状态
          if (index == advertisements.length) {
            return Padding(
              padding: const EdgeInsets.symmetric(vertical: 16),
              child: Center(
                child: loadMoreStatus == AdvertisementLoadMoreStatus.LOADING
                    ? const CircularProgressIndicator()
                    : const SizedBox.shrink(),
              ),
            );
          }
          return AdvertisementCard(data: advertisements[index]);
        },
        separatorBuilder: (BuildContext context, int index) {
          return const SizedBox(height: 10);
        },
      ),
    ),
  );
}

第二步:修改加载状态触发逻辑

在onNotification方法中切换加载状态时调用setState,触发UI刷新显示加载指示器:

bool onNotification(ScrollNotification notification) {
  if (notification is ScrollUpdateNotification) {
    if (scrollController.position.maxScrollExtent > scrollController.offset &&
        scrollController.position.maxScrollExtent - scrollController.offset <=
            50) {
      if (loadMoreStatus == AdvertisementLoadMoreStatus.STABLE) {
        // 调用setState更新状态,触发UI展示加载指示器
        setState(() {
          loadMoreStatus = AdvertisementLoadMoreStatus.LOADING;
        });
        AdvertisementProdRepository.fetchAdvertisements(currentPageNumber + 1)
            .then((advertisementObject) {
          currentPageNumber = advertisementObject.pageNumber;
          loadMoreStatus = AdvertisementLoadMoreStatus.STABLE;
          setState(() => advertisements.addAll(advertisementObject.items));
        });
      }
    }
  }
  return true;
}

修改完成后,当触发加载更多逻辑时,列表底部会自动展示CircularProgressIndicator,数据请求完成加载后指示器会自动隐藏,新的广告内容会插入到列表中。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 18:42:01