2.3 Modifiers

Modifiers allow you to decorate or augment a composable. Simply having composables is not enough for front-end development. You also need to customize the behavior and appearance of composable functions.

Modifiers are mainly used for layout modification, appearance customization, and event handling. We will first look at an example of how to use modifiers, and then dive into the specific usages.

Example Usage

@Composable
private fun greeting(name: String){
    Column(
        modifier = Modifier
            .padding(8.dp)
    ){
        Text(text="Hello,")
        Text(text=name)
    }
}

Modifiers are applied to a composable by using the modifier parameter. Here we are adding padding to the Column composable.

Chaining modifiers

Modifiers can be chained together to apply multiple effects.

@Composable
private fun greeting(name: String){
    Column(
        modifier = Modifier
            .padding(8.dp)
            .fillMaxWidth()
            .background(Color.Red)
    ){
        Text(text="Hello,")
        Text(text=name)
    }

Here, we have the same composables but we are applying three modifiers to the Column, instead of one.

The order of modifiers can affect the result, so it's important to chain them thoughtfully. Folloiwng is an example of how the same modifier functions can give different results if the order is changed

Text(
    text = "Background first, then padding",
    modifier = Modifier
        .background(Color.Green)
        .padding(16.dp)
)

Text(
    text = "Padding first, then background",
    modifier = Modifier
        .padding(16.dp)
        .background(Color.Green)
)

Some Common Modifiers

Layout Modification

  • Modifier.padding() - Adds padding around a composable.

  • Modifier.size(), Modifier.width(), Modifier.height() - Sets the size of a composable.

  • Modifier.fillMaxSize(), Modifier.fillMaxWidth(), Modifier.fillMaxHeight() - Makes a composable fill available space.

  • Modifier.align() - Aligns a composable within a parent layout.

Appearance Customization

  • Modifier.background() - Sets the background color or drawable.

  • Modifier.border() - Adds a border with specified color, width, and shape.

  • Modifier.clip() - Clips the composable to a specified shape.

Behavior Modification

  • Modifier.clickable() - Makes a composable respond to click events.

  • Modifier.draggable(), Modifier.scrollable() - Adds drag or scroll behavior.

Last updated