Patrick Michalik

Adding modifiers conditionally in Jetpack Compose

When working with Jetpack Compose, you may need to apply a modifier only under a specific condition. A common approach looks like this:

Modifier.then(
    if (clickable) Modifier.clickable(onClick) else Modifier
)

While this is a valid way of adding a modifier conditionally, it lacks conciseness. For a more streamlined solution, create a helper modifier for conditional application, leveraging the fact that modifiers are defined as extension functions:

fun Modifier.thenIf(
    condition: Boolean,
    other: Modifier.() -> Modifier,
) = if (condition) other() else this

This modifier can be used as follows:

Modifier.thenIf(clickable) { clickable(onClick) }

When adding multiple modifiers, remember to chain them:

Modifier.thenIf(clickable) { clickable(onClick).color(Color.Blue) }

When the condition is that a given value is not null, type-safe access to the not-null value may be required. The following modifier facilitates this:

fun <T> Modifier.thenIfNotNull(
    value: T?,
    other: Modifier.(T) -> Modifier,
) = if (value != null) other(value) else this

Use it like so:

Modifier.thenIfNotNull(onClick) { clickable(it) }
© 2018–2024 Patrick Michalik