xxfast
05/04/2022, 2:18 AMmodifier = modifier
.let { if(canBeExpanded) it.clickable { expanded = !expanded } else it }
Francesc
05/04/2022, 2:19 AMthen
,
modifier = modifier.then(
if (condition) Modifier.clickable {} else MOdifier
)
xxfast
05/04/2022, 2:23 AMmodifier = modifier
.then( if(canBeExpanded) Modifier.clickable { expanded = !expanded } else Modifier)
.run { if(canBeExpanded) clickable { expanded = !expanded } else this }
trying to avoid that else
part, apply
compiles but doesn't seem to work, not sure why
.apply { if(canBeExpanded) clickable { expanded = !expanded } }
Francesc
05/04/2022, 2:30 AMcomposed
then
seems to be the preferred approach, if you check the compose code that's what it uses under the hood, for instance
@Stable
@Suppress("ModifierInspectorInfo")
fun Modifier.fillMaxWidth(/*@FloatRange(from = 0.0, to = 1.0)*/ fraction: Float = 1f) =
this.then(if (fraction == 1f) FillWholeMaxWidth else createFillWidthModifier(fraction))
xxfast
05/04/2022, 2:34 AMfun Modifier.on(condition: Boolean, block: Modifier.() -> Modifier): Modifier =
if(condition) block() else this
can make the call site look like
modifier = modifier
.on(canBeExpanded) { clickable { expanded = !expanded } }
but this comes at the cost of indirection i guessFrancesc
05/04/2022, 2:36 AMenabled
to control whether it's actually clickable?xxfast
05/04/2022, 2:36 AMFrancesc
05/04/2022, 2:37 AMclickable
fun Modifier.clickable(
enabled: Boolean = true,
onClickLabel: String? = null,
role: Role? = null,
onClick: () -> Unit
)
enabled = condition
xxfast
05/04/2022, 2:38 AMagrosner
05/04/2022, 1:42 PM/**
* Convenience for modifiers that should only apply if [condition] is true.
* [elseFn] useful for conditional else-logic.
*/
inline fun Modifier.thenIf(
condition: Boolean,
modifierFn: Modifier.() -> Modifier,
) = this.let {
if (condition) {
it.modifierFn()
} else {
it
}
}
/**
* Convenience for modifiers that should only apply if [condition] is true.
* [elseFn] useful for conditional else-logic.
*/
inline fun Modifier.thenIf(
condition: Boolean,
modifierFn: Modifier.() -> Modifier,
elseFn: Modifier.() -> Modifier,
) = this.let {
if (condition) {
it.modifierFn()
} else {
it.elseFn()
}
}
Colton Idle
05/04/2022, 8:16 PMZach Klippenstein (he/him) [MOD]
05/10/2022, 3:03 PMapply
doesn't work because apply returns its receiver, not the last expression in the lambda. You'd want run
or let
.