LazyColumn 是 Compose 中最常用的列表组件,掌握其高级用法对于构建高性能应用至关重要。
一、使用稳定的 Key
LazyColumn {
items(
items = articles,
key = { article -> article.id } // 唯一稳定的 key
) { article ->
ArticleCard(article)
}
}
二、Sticky Headers
@OptIn(ExperimentalFoundationApi::class)
LazyColumn {
groups.forEach { (letter, contacts) ->
stickyHeader {
Text(letter)
}
items(contacts) { contact ->
ContactItem(contact)
}
}
}
三、LazyGrid
LazyVerticalGrid(
columns = GridCells.Adaptive(minSize = 160.dp)
) {
items(items, key = { it.id }) { item ->
ItemCard(item)
}
}
四、使用 derivedStateOf
val showButton = remember {
derivedStateOf { listState.firstVisibleItemIndex > 0 }
}
// 只有 showButton 变化时才重组
if (showButton.value) {
ScrollToTopButton()
}
五、最佳实践
- ✅ 始终提供稳定的 key
- ✅ 使用 contentType 优化复用
- ✅ 使用 derivedStateOf 减少重组
- ✅ 避免在 items 中创建新 lambda
- ✅ 使用 animateItem 添加动画
总结
- Key:提供稳定唯一标识
- contentType:优化 item 复用
- Sticky Header:分组固定头部
- LazyGrid:网格布局