Add conditional Modifier without sacrificing its fluent API

It’s been a while since the first stable version of Jetpack Compose was released and a lot of developers have finally decided to give it a try. At first everything looked super easy (and it is somehow!) but when it’s time to create some Composable component based in a very specific use case, that’s when those happy-case examples from tutorials are not enough and we need to start asking/searching on the Internet about those particular corner cases. The “corner case” described in this article is not as corner as one might think but it is related to a situation in which is easy to fall.
I was writing a Composable that looked like this:
And I was using my isFixed
param to determine the background color. The next thing I wanted to be configured based on that same flag was the clickable
modifier. My first approach was this (Spoiler: it didn’t work):
After executing the above code I was expecting some of my Composable Cells to be clickable but non of them was.
My sin was to believe that Modifier chain methods reuse the same Modifier instance, and that is incorrect: every chain method returns a new Modifier instance. Since apply
function executes methods over its receiver after returning that same receiver, clickable
method returned instance was being ignored, thus it wasn’t having any effect.
Some simple solution would have been to write something like this:
However, we have lost the confort of the fluent API that Modifier class provides. If I had used another Kotlin function such as run
I would have achieved the desired behavior I expected in my first attempt with apply
, because it would have forced me to return and explicit Modifier in its lambda. Inspired on run
implementation, I wrote this Modifier extension function:
And then my Composable can finally have both expected behavior and a pretty look:
And that’s all, this is probably an obvious thing that might haven’t be a problem for most of you but I hope it can help! Thanks for reading!