@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.
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
modifierparameter, and pass thatmodifierto its first child that emits UI. Doing so makes your code more reusable and makes its behavior more predictable and intuitive.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With