Compose 列表优化进阶:LazyColumn 高级技巧

2024-06-19 · 24 min · 性能

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()
}

五、最佳实践

总结