https://kotlinlang.org logo
#compose
Title
# compose
t

Tash

03/09/2021, 12:36 AM
Having some trouble understanding the
key
Composable. Noticed its usage in Jetcaster’s Pager:
Copy code
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”.
👍 1
a

Albert Chang

03/09/2021, 1:03 AM
Taking the example in the doc:
Copy code
for (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.
🙏 2
You can run this code and see the difference:
Copy code
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() })
                }
            }
        }
    }
}
t

Tash

03/09/2021, 2:32 AM
Thank you! Will check out that snippet.