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

LazyColumn内LazyRow项状态变更后无法即时更新的问题

解决LazyRow内容不实时更新的问题

问题根源在于LazyColumn中的item未为动态变化的收藏列表提供唯一标识,导致Compose无法感知数据变化触发重组;同时LazyRow内的items未指定唯一key,易引发项复用错误。

修复步骤:

  • 为LazyColumn中的item添加基于收藏列表内容的key
  • 为LazyRow内的items指定Session的唯一标识作为key

修改后的代码如下:

@Composable
fun SessionsScreen(onSessionClick: (Session) -> Unit, viewModel: SessionsViewModel = 
hiltViewModel()) {
    val sessionsStateFlow by viewModel.sessionsStateFlow.collectAsState()
    val favouriteStateFlow by viewModel.favouritesStateFlow.collectAsState()

    LazyColumn(
        modifier = Modifier
            .padding(horizontal = 20.dp)
            .fillMaxSize()
    ) {
        favourite(favouriteStateFlow)
    }
}

fun LazyListScope.favourite(favouritesState: List<Session>) {
    // 为外层item添加key,收藏列表变化时触发重组
    item(key = "favourites_row_${favouritesState.hashCode()}") {
        LazyRow {
            if (favouritesState.isEmpty()) {
                item { Text(text = stringResource(id = R.string.no_favourites)) }
            }
            // 指定Session唯一id作为key,避免项复用导致更新异常
            items(favouritesState, key = { session -> session.id }) {
                Favourite(it)
            }
        }
    }
}

原理说明:

  • 外层item的key:通过收藏列表的hashCode生成key,列表内容变化时hashCode改变,Compose会识别为新item,触发LazyRow的重组更新。
  • LazyRow items的key:用Session的唯一id作为key,让Compose准确识别每个列表项的身份,避免数据变化时复用旧布局,确保内容实时更新。

内容的提问来源于stack exchange,提问作者Илья Жиленков

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 09:05:59