April 24, 2022
While using Jetpack Compose, you may have run into an instance where you needed to add a modifier only if a certain condition was true. You may have used a solution similar to this one:
This is certainly a valid way of adding a modifier conditionally, but it’s not particularly concise. To make the task at hand easier, you can instead create a helper modifier for conditional modification, which is possible because modifiers are defined as extension functions.
This modifier can be used as follows.
If you need to add multiple modifiers, remember to chain them:
Besides adding a modifier under a certain condition, you may need to add a modifier if a value is not null. In such a case, you’ll typically also want to use the not-null value in the modifier. In order to avoid using not-null assertion, you can once again create a helper modifier:
This modifier can be used as follows.