在状态更改时更新单个 LazyColumn 项目

问题描述 投票:0回答:1

我需要在我的

LazyRow
中显示最喜欢的会话,这是
LazyColumn
的项目,但是如果最喜欢的会话列表发生变化,要更新
LazyRow
中的内容,我需要向下滚动,而
LazyRow
完全消失在顶部,然后返回我的
LazyRow

这是我的代码:

@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 {
        LazyRow {
            if (favouritesState.isEmpty()) {
                item { Text(text = stringResource(id = R.string.no_favourites)) }
            }
            items(favouritesState) {
                Favourite(it)
            }
        }
    }
}
android kotlin android-jetpack-compose android-jetpack lazycolumn
1个回答
0
投票

要在收藏会话列表更改时更新 LazyRow 中的内容,您应该使用 items 函数中的 key 参数。这确保 Compose 可以区分不同的项目并正确更新它们。

    @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 {
            LazyRow {
                if (favouritesState.isEmpty()) {
                    item { Text(text = stringResource(id = R.string.no_favourites)) }
                }
                items(favouritesState) { session ->
                    Favourite(session, key = session.id) {
                        // Add any interaction logic here
                    }
                }
            }
        }
    }
    
    @Composable
    fun Favourite(session: Session, onClick: () -> Unit) {
        // Your Favourite item composable content here
        // For example:
        Box(
            modifier = Modifier
                .padding(8.dp)
                .clickable { onClick() }
        ) {
            Text(text = session.title)
        }

}
© www.soinside.com 2019 - 2024. All rights reserved.