Insert composable from another fun into main ConstraintLayout

I want to create one custom composable in a fun, and then add that composable into another fun that contains my main ConstraintLayout with all the composables for the layout.
I am having trouble with the constraints when I try to do this, I get the composable into the ConstraintLayout, but it is stuck in the top left/start corner.

How can I correctly add constraints to this composable that is built and comes from another fun into my main ConstraintLayout fun?

My code:

@Composable
fun MainConstraintLayout() {
    ConstraintLayout {
        val (view1, view2) = createRefs()

        Button(onClick = { /*....*/ },
            modifier = Modifier.constrainAs(view1) {
                top.linkTo(parent.top)
                start.linkTo(parent.start)
                end.linkTo(parent.end)
            }
        ) { Text("view1, correct constraints") }

        // How can I constraint this view (below) to the bottom of view1?
        MyOneComposable()
    }
}

@Composable
fun MyOneComposable() {
    Button(onClick = { /*....*/ }) {
        Text(text = "My one composable button")
    }
}

>Solution :

You need to pass Modifier parameter into your MyOneComposable:

@Composable
fun MyOneComposable(
    modifier: Modifier,
) {
    Button(onClick = { /*....*/ }, modifier = modifier) {
        Text(text = "My one composable button")
    }
}

So you can apply ref modifier from ConstraintLayout:

MyOneComposable(Modifier.constraintAs(view2) { ... })

Leave a Reply