Composable Function

key

key is a utility composable that is used to "group" or "key" a block of execution inside of a composition.

LocallyUniqueKeys

@Sampled
@Composable
fun LocallyUniqueKeys() {
    for (user in users) {
        key(user.id) { UserPreview(user = user) }
    }

    for (user in users.filter { isAdmin }) {
        key(user.id) { Friend(friend = user) }
    }
}

NotAlwaysUniqueKeys

@Sampled
@Composable
fun NotAlwaysUniqueKeys() {
    for ((child, parent) in relationships) {
        key(parent.id) {
            User(user = child)
            User(user = parent)
        }
    }
}

MoreCorrectUniqueKeys

@Sampled
@Composable
fun MoreCorrectUniqueKeys() {
    for ((child, parent) in relationships) {
        key(parent.id to child.id) {
            User(user = child)
            User(user = parent)
        }
    }
}

TwoInputsKeySample

@Sampled
@Composable
fun TwoInputsKeySample() {
    for (element in elements) {
        val selected by key(element.id, parentId) { remember { mutableStateOf(false) } }
        ListItem(item = element, selected = selected)
    }
}
Jetpack Compose beyond MaterialFree components, screens and templates for apps that don’t look like Google’s. Copy them into your app, or let your coding agent add them.Browse for free

Content updated: