ifTrue Modifier
Modifiers are one of my favorite features of Jetpack Compose. They allow you to visually update a composable function and add more functionality to them. One of the reasons they are so elegant is because you can chain them. This results in an intuitive API that's easy to work with. Here's an example-
@composable
fun MyComponent() {
Box(
modifier = Modifier
.fillMaxWidth()
.background(Color.Cyan)
.padding(16.dp)
.
) {...}
}
Note: The order in which the Modifiers are applied makes a difference to the end result.
When using these API's in real world scenarios, you are often in a situation where you want to apply Modifiers only when a condition is met. Let's look at one such example-
fun MyComponent(
isError: Boolean
) {
var modifierChain = Modifier.fillMaxWidth()
if (isError) {
modifierChain = modifierChain.background(Color.Red)
}
Box(
modifier = modifierChain
.padding(16.dp)
) {...}
}
Here, we want to add the background
modifier only if the isError
prop is true. In order to make sure we chain them properly, we need to hold a reference to the
modifier chain and add the background
modifier to this reference when isError
is true. This can get out of hand really quickly when you have multiple conditions that
determine which Modifier needs to be applied.
* ifTrue Modifier has entered the chat *
Using this simple and elegant snippet, I can add the conditional logic in the chain itself and the code looks significantly cleaner now!
fun MyComponent(
isError: Boolean
) {
Box(
modifier = Modifier.fillMaxWidth()
.ifTrue(isError) { background(Color.Red) }
.padding(16.dp)
) {...}
}
Slick isn't it?
inline fun Modifier.ifTrue(predicate: Boolean, builder: () -> Modifier) = | |
then(if (predicate) builder() else Modifier) |
Maker OS is an all-in-one productivity system for developers
I built Maker OS to track, manage & organize my life. Now you can do it too!