如何使用GlideImage统计列表中成功加载的图片数量?
解决GlideImage加载成功计数器无限递增的问题
问题核心原因有两点:
- 当
successfulImageCount.value更新时,会触发整个ImageLoaderComposable重组,urls.forEach会重新执行,所有GlideImage组件被重新创建并发起加载请求,成功回调再次触发计数器增加,形成无限循环。 - 列表中存在重复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
相关产品推荐
相关产品推荐

