Elye
Elye

Reputation: 60361

How can I make a composable function with `weight` modifier?

When I have

Column {
    Button(onClick = { /*TODO*/ },) {
        Text("Original Window")
    }
    Button(onClick = { /*TODO*/ }) {
        Text("Fit System Window")
    }
}

I can create a common composable function

@Composable
fun MyButton(
    onClick: () -> Unit,
    content: @Composable RowScope.() -> Unit
) {
    Button(
        onClick = onClick,
        content = content
    )
}

Column {
    MyButton(onClick = { /*TODO*/ },) {
        Text("Original Window")
    }
    MyButton(onClick = { /*TODO*/ }) {
        Text("Fit System Window")
    }
}

However when I have

Column {
    Button(onClick = { /*TODO*/ },
        modifier = Modifier.weight(1f)) {
        Text("Original Window")
    }
    Button(onClick = { /*TODO*/ },
        modifier = Modifier.weight(1f)) {
        Text("Fit System Window")
    }
}

I cannot create below

@Composable
fun MyButton(
    onClick: () -> Unit,
    content: @Composable RowScope.() -> Unit
) {
    Button(
        onClick = onClick,
        modifier = Modifier.weight(1f),
        content = content
    )
}

Column {
    MyButton(onClick = { /*TODO*/ },) {
        Text("Original Window")
    }
    MyButton(onClick = { /*TODO*/ }) {
        Text("Fit System Window")
    }
}

This is because weight modifier is under ColumnScope interface.

How can I make a composable function with weight modifier?

Upvotes: 21

Views: 3332

Answers (1)

Elye
Elye

Reputation: 60361

Looks like I just need to just create an extension from of ColumnScope

@Composable
fun ColumnScope.MyButton(
    onClick: () -> Unit,
    content: @Composable RowScope.() -> Unit
) {
    Button(
        onClick = onClick,
        modifier = Modifier.weight(1f),
        content = content
    )
}

Upvotes: 33

Related Questions