Jetpack Compose: Modifiers fundamentals
Modifiers in Jetpack Compose are great. It's a consistent way to give additional functionality and shape to your composables.
Most people compare modifiers with XML attributes in the old Android UI world. But they are quite different. In this post, I will cover the biggest differences I noticed, that makes them way more powerful and flexible than attributes.
Repeatability
Although it looks like the Modifier
follows the builder pattern, it's not. You are not setting a value to a property when calling each method. You are applying operations when calling those methods. This means you can call each method multiple times and each method will be applied again and again.
Where might this be useful? One interesting example is the use of decorating modifiers to decorate your composables. For instance, in the snippet below we can create two borders around our Text
by calling border
multiple times.
Text(
"Hello word",
modifier = Modifier
.border(1.dp, Color.Black)
.padding(16.dp)
.border(1.dp, Color.Black)
)
Ordering
Ordering matters (you might have figured it out from the previous snippet already). This is interesting in the sense that dedicated XML attributes of the old Android UI world can be expressed by different ordering of Modifier
methods.
For instance, there are no different padding and margin Modifier
methods. You accomplish the same results using the different ordering of the padding
method.
Text(
"Hello world",
modifier = Modifier
.padding(8.dp) // "Margin"
.clip(RoundedCornerShape(4.dp))
.background(Color.Gray)
.padding(16.dp) // "Padding"
)
Consistency
The list of built-in Compose Modifiers can be applied to (almost) every composable that accepts a Modifier
(with the exception of some Modifier
s that are restricted to specific scopes, e.g. RowScope, BoxScope). This is unlike the XML attributes that had specific attributes for specific elements. It creates uniformity and it's easier to remember how to accomplish common tasks.
Such a common task is how to set a click handler. Just set the clickable
method and you are done.
Text(
"Hello world",
modifier = Modifier
.clickable(
onClick = {
// Do things
})
)
Hopefully, by now you have grasped some fundamentals on how Modifer
works that will make your life navigating around Compose a bit easier.
Happy coding!