Tash
03/09/2021, 12:36 AMkey
Composable. Noticed its usage in Jetcaster’s Pager:
for (page in minPage..maxPage) {
val pageData = PageData(page)
val scope = PagerScope(state, page)
key(pageData) {
Box(contentAlignment = Alignment.Center, modifier = pageData) {
scope.pageContent()
}
}
}
What exactly is the purpose of key
here?
Would love some more insight into how/what it does in general. The implementation of key
doesn’t betray its functionality, since the function params are “unused”.Albert Chang
03/09/2021, 1:03 AMfor (user in users) {
key(user.id) { UserPreview(user = user) }
}
Every UserPreview
is tied to a specific user, but Compose runtime doesn't understand that. Without the key
, the runtime will simply recompose by order, which means that if you remove an item from users
which is not at the end, the recomposition target will be wrong.
Using key
can avoid unnecessary recomposition when the composable is stateless, and avoid bugs when the composable is stateful.var list by remember { mutableStateOf((1..10).toList()) }
Column(horizontalAlignment = Alignment.CenterHorizontally) {
Button(onClick = { list = list.subList(1, list.size) }) {
Text(text = "Remove First")
}
Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceEvenly) {
Column {
Text("Without key")
list.forEach {
Text(text = remember { it.toString() })
}
}
Column {
Text("With key")
list.forEach {
key(it) {
Text(text = remember { it.toString() })
}
}
}
}
}
Tash
03/09/2021, 2:32 AM