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

如何修复Jetpack Compose中LazyGrid滚动卡顿的性能问题?

解决LazyVerticalGrid滚动卡顿问题

核心问题定位

你遇到的滚动卡顿,根源在于普通MutableList无法被Jetpack Compose精准感知元素变化,每次修改列表时会触发整个LazyGrid的全量重组,导致滚动时性能急剧下降。即使移除AsyncImage或ReorderableItem,这个核心问题依然存在。

具体修复步骤

  1. 替换普通MutableList为MutableStateList
    Compose的mutableStateListOf()会跟踪元素的增删改操作,仅通知对应Item进行重组,而非全列表刷新。修改代码如下:
// 替换原来的val images = // mutable List<Uri>
val images = remember { mutableStateListOf<Uri>() }
  1. 优化LazyGrid的Items绑定方式
    当前使用items(images.size)通过索引取元素的方式,容易引发不必要的重组。改为直接绑定列表元素,并指定唯一Key:
// 用itemsIndexed同时获取索引和元素,更适配你的点击逻辑
itemsIndexed(images, key = { _, item -> item }) { index, item ->
    ReorderableItem(
        state,
        key = item,
        orientationLocked = false,
        index = index,
    ) { isDragging ->
        ElevatedCard(
            onClick = { startCrop(index) },
            modifier = Modifier.shadow(
                if (isDragging) 12.dp else 0.dp,
                RoundedCornerShape(8.dp)
            ),
            enabled = creatingPdf.value.not()
        ) {
            Box {
                AsyncImage(
                    model = item,
                    contentDescription = null,
                    contentScale = ContentScale.Crop,
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(230.dp),
                    alpha = if (isDragging) 0.8f else 1f,
                )
            }
        }
    }
}
  1. 确认ReorderableState的操作效率
    rememberReorderableLazyGridState的onMove逻辑无需修改,因为MutableStateList的add/removeAt操作已经是Compose优化过的状态更新。

额外优化建议

  • 确保creatingPdf是使用remember { mutableStateOf(false) }创建的稳定State,避免不必要的重组触发。
  • 如果列表元素数量极大(上千条),可以考虑分页加载,减少单次渲染的Item数量。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 00:10:48