Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass children in Jetpack Compose to a custom composable?

I am curious if it is possible to pass in composables to a custom composables block. Which is then rendered in its definition. I was thinking a vararg + function literal approach could be taken and couldn't find any information.

//definition
@Composable
fun Content() {
    Row(modifier = Modifier.fillMaxWidth()) {
        //insert a(), b(), ..., z() so that they render in the row
    }
}

//usage
Content() {
    a()
    b()
    ...
    z()
}

Does something like this exist already? You are able to use Jetpack Compose this way. The row implementation must handle the Text somehow.

Row(){
    Text("a")
    Text("b")
    Text("c")
}
like image 562
MaxGDN Avatar asked Dec 11 '20 21:12

MaxGDN


People also ask

What is composable in jetpack compose?

Jetpack Compose is built around composable functions. These functions let you define your app's UI programmatically by describing how it should look and providing data dependencies, rather than focusing on the process of the UI's construction (initializing an element, attaching it to a parent, etc.).

How are composable is redrawn?

When the state changes, the composable functions are called again with the new data. This causes the UI elements to be redrawn--this process is called recomposition.

What is a modifier in jetpack compose?

Modifiers allow you to decorate or augment a composable. Modifiers let you do these sorts of things: Change the composable's size, layout, behavior, and appearance. Add information, like accessibility labels.

Is jetpack compose stable now?

Today, we're releasing version 1.2 of Jetpack Compose, Android's modern, native UI toolkit, continuing to build out our roadmap.


1 Answers

After looking at the implementation of Row, RowScope and finding this piece of documentation. This can be achieved by the following code sample. The content function parameter with the type of @Composable() () -> Unit gets passed down into the row.

//definition
@Composable
fun MyCustomContent(
    modifier: Modifier = Modifier,
    content: @Composable() () -> Unit
) {
    Row(modifier = modifier) {
        content()
    }
}

//usage
MyCustomContent() {
    a()
    b()
    z()
}
like image 184
MaxGDN Avatar answered Sep 29 '22 03:09

MaxGDN