galex
06/21/2022, 7:50 AMinline fun Modifier.optional(
block: Modifier.() -> Modifier?
) = block() ?: this
And we use it this way:
.optional {
frameColor?.let {
border(4.dp, it, CircleShape)
}
}
It there a better way to do this? 🤔Zoltan Demant
06/21/2022, 8:06 AMinline fun <T> Modifier.conditional(
value: T?,
modifier: (T) -> Modifier
): Modifier {
return conditional(
condition = value != null,
modifier = {
modifier(checkNotNull(value))
}
)
}
inline fun Modifier.conditional(
condition: Boolean,
modifier: () -> Modifier
): Modifier {
return when {
condition -> then(modifier())
else -> this
}
}
yschimke
06/21/2022, 8:21 AMcondition: () -> Boolean
and use Modifier.composed? Does that avoid extra work in the compose phase? (I don't know answer but am curious)galex
06/21/2022, 8:31 AMcheckNotNull
! The only thing I disliked in your solution is that you have to create a new Modifier in the body of your modifier lambda, so I changed it to
inline fun <T> Modifier.conditional(
value: T?,
modifier: Modifier.(T) -> Modifier
): Modifier {
return conditional(
condition = value != null,
modifier = {
modifier(checkNotNull(value))
}
)
}
inline fun Modifier.conditional(
condition: Boolean,
modifier: () -> Modifier
): Modifier {
return when {
condition -> then(modifier())
else -> this
}
}
So now I can do:
Modifier
.someStuff(...)
.conditional(frameColor) {
border(4.dp, it, CircleShape)
}
Thank you that's exactly what I was looking for! :-DZoltan Demant
06/21/2022, 8:35 AMAlbert Chang
06/21/2022, 9:02 AMModifier.composed
isn’t an optimization. It’s actually more expensive than a non-composed modifier. You should only use it when you need to call composable functions or read composition locals.
There is even a lint warning when you use it unnecessarily.yschimke
06/21/2022, 9:04 AM