Is there a better way to deduplicate this sort of ...
# compose
c
Is there a better way to deduplicate this sort of code in compose?
Copy code
if (myEvent != null) {
    Card(modifier = modifier, elevation = 2.dp, onClick = myEvent) {
        content()
    }
} else {
    Card(modifier = modifier, elevation = 2.dp) {
        content()
    }
}
m
hmmm maybe a lambda for onClick?
Copy code
onClick = {
    myEvent?.let{ it() }
}
e
that'll make the card clickable in all cases, with click action doing nothing sometimes. that's different than a card without a click handler
m
maybe this? https://stackoverflow.com/questions/71238475/how-can-i-make-composables-unclickable-preferrably-by-its-modifier but to set the onClick as a nullable parameter and turn the boolean when not null
e
as an aside, consider using
movableContentOf()
so that the inner content isn't recomposed when the click is enabled/disabled, e.g.
Copy code
val composable = movableContentOf { content() }
if (...) {
    Card(...) { composable() }
} else {
    Card(...) { composable() }
}
z
Oh that's neat. I didn't consider the content getting recomposed. Might even fix a few issues in my app
a
You can just apply clickable modifier conditionally on the child of
Card
(which is equivalent to using the overload with
onClick
parameter):
Copy code
Card(elevation = 2.dp) {
    Box(
        modifier = if (onClick != null) {
            Modifier.clickable(onClick = onClick)
        } else {
            Modifier
        }
    ) {
        content()
    }
}