How the order of Modifiers matters with Jetpack Compose

Abhishek Jangra
3 min readApr 4, 2023

--

Hi 👋

When you start writing Compose Layouts, you learn about modifiers which are used to decorate your Views. In this article, I want to talk about how your thought process needs to evolve going from XML properties to Compose modifiers. Let’s take an example,

To achieve this with XML you will need 2 files,

With Compose, you can chain a few modifiers and achieve the result,

Sounds simple, right? It really is. But there is one very important detail I want to share with you.

With XML, padding and background are properties exposed on the TextView , different Views can expose different properties and it does NOT matter in what order you define the XML properties, the result will be the same.

While on Compose, these are drawn as layers of UI decorations around any Composable starting from the end of the modifier chain.

Back to the example, let’s change the order of modifiers we wrote,

That does not match the design 🙅🏻‍♂️

This is why Compose requires a shift in the mental models we have while writing UI, looking at the design you should be able to form the layers in your mind,

If you add the background first and then the padding, the color would only be behind the Text and not the space that you added with padding() .

It takes some effort, but once you get used to it the benefits are there. Modifiers become these reusable design pieces in your code which can be applied anywhere. And because all of this is Kotlin code, you can even store a chain of modifiers as a val and use it in multiple places, no need to create a Custom View for reusing a simple UI element.

This was a crisp write up based on information from topics I am working on currently, there will be more of these coming in the future so make sure you follow!

--

--