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

iih3973s  于 12个月前  发布在  Android
关注(0)|答案(1)|浏览(173)

我需要在我的LazyRow中显示最喜欢的会话,这是LazyColumn的项目,但如果最喜欢的会话列表cahnges,要更新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)
            }
        }
    }
}

字符串

epggiuax

epggiuax1#

要在收藏夹会话列表发生变化时更新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)
        }

}

字符串

相关问题