Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

compose how to add alignment to a Composable function child

@Composable
fun Root() {
  Box {
    Text("foo")
    BarView()
  }
}
@Composable
fun BarView() {
  Text("bar")
}

this is my code example, i want to set BarView align to TopEnd. if i change BarView() to fun BoxScope.BarView(), then BarView cannot reuse in other widget. if i wrap BarView with a Box, it will have an extra layer.

Box {
    Text("foo")
    Box(modifier = Modifier.align(Alignment.TopEnd)) {
      BarView()
    }
  }

Is there a better way to do this, or wrap a Box is just fine.

like image 378
Jade Avatar asked Feb 21 '26 02:02

Jade


1 Answers

You can pass in a Modifier to the BarView Composable:

@Composable
fun BarView(modifier: Modifier = Modifier) {
    Text(
        modifier = modifier
        text = "bar"
    )
}

Then, you can use it in any parent Composable, but still can pass down any Modifier that requires a certain scope:

@Composable
fun Root() {
    Box {
        Text("foo")
        BarView(
            modifier = Modifier.align(Alignment.TopEnd)  // pass BoxScope Modifier
        )
    }
}

@Composable
fun ColumnExample() {
    Column {
        Text("foo")
        BarView(
            modifier = Modifier.weight(1f)  // pass ColumnScope Modifier
        )
    }
}

This approach also is best practice according to the Modifier documentation:

It's a best practice to have all of your composables accept a modifier parameter, and pass that modifier to its first child that emits UI. Doing so makes your code more reusable and makes its behavior more predictable and intuitive.

like image 68
BenjyTec Avatar answered Feb 23 '26 03:02

BenjyTec



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!