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

如何使用GlideImage统计列表中成功加载的图片数量?

解决GlideImage加载成功计数器无限递增的问题

问题核心原因有两点:

  1. 当successfulImageCount.value更新时,会触发整个ImageLoader Composable重组,urls.forEach会重新执行,所有GlideImage组件被重新创建并发起加载请求,成功回调再次触发计数器增加,形成无限循环。
  2. 列表中存在重复URL,即使没有重组,重复URL的加载成功事件也会被重复统计。

修复代码

fun ImageLoader() {
    val urls = listOf(
        "https://www.example.com/image1.jpg",
        "https://www.example.com/image2.jpg",
        "https://www.example.com/image3.jpg",
        "https://www.example.com/image1.jpg",
    )
    val successfulImageCount = remember { mutableStateOf(0) }
    // 用remember保存已统计的图片索引,避免重复计数(适配重复URL场景)
    val loadedIndices = remember { mutableSetOf<Int>() }

    Column(modifier = Modifier.fillMaxSize()) {
        urls.forEachIndexed { index, url ->
            // 传入index作为key,稳定每个GlideImage的组件实例,防止重组时重复创建
            GlideImage(
                key = index,
                imageModel = { url },
                success = { status: GlideImageState.Success, image: Painter ->
                    // 仅当该图片未被统计过,才递增计数器
                    if (loadedIndices.add(index)) {
                        successfulImageCount.value++
                    }
                    Image(painter = image, contentDescription = "")
                },
                modifier = Modifier.size(80.dp),
            )
        }

        Text(text = "Images uploaded correctly: ${successfulImageCount.value}")
    }
}

关键修复点说明

  • loadedIndices集合:通过remember持久化存储已成功加载的图片索引,利用集合的唯一性,确保每个图片仅被统计一次,即使URL重复也能正确计数。
  • key = index参数:给每个GlideImage指定唯一key,让Compose在重组时能识别到每个图片组件的身份,避免重复创建组件和发起加载请求。
  • 条件计数:在成功回调中先判断索引是否已加入集合,只有首次成功加载时才更新计数器,从根源上阻止无限递增。

内容的提问来源于stack exchange,提问作者D.Sanxhez

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 16:12:48