Basic question but I can't find a good answer: how...
# compose
m
Basic question but I can't find a good answer: how do I apply a
Modifer
conditionally? Like
previousModifier().apply{ if(hasPadding) padding(4.dp) }
, except that doesn't work. (I know why it doesn't work, but I don't know a nice method that works)
r
You should call Modifier.then(if Moidier.padding() else Modifier)
e
Copy code
inline fun Modifier.modifyIf(
  condition: Boolean,
  then: Modifier.() -> Modifier
): Modifier = if (condition) then() else this
.modifyIf(hasPadding) { padding(4.dp) }
2
m
Thank you, I was looking for something like that built-in, but a custom extension works too!
c
The problem with your original snippet is that
apply
will return the original object (
this
), so your changes are thrown away.
.run { }
would solve the problem with your snippet as well, but you have to add an
else
block similar to @Eric did.
m
@Csaba Kozák Like I said, I know why the
apply
doesn't work, and only used it to convey what I am looking for. : ) I tried
run
but found it quite verbose with the
else
, hence my question. Hiding it in an extension like Eric suggested is a good solution.
c
My bad, i missed that part!
c
I tried this in my codebase and it somehow completely messes with my layout when I conditionally add a clickable{} /shruggie