I'm learning about `CompositionLocal` and when/ho...
# compose
b
I'm learning about
CompositionLocal
and when/how to use it. Does this seem like a valid use case: Using a Material theme, the designer provided direction for Outlined Buttons ... When a button is displayed on the surface or background color, it should use the Theme's
Secondary
color. When a button is displayed on another color, it should use that color's "on" Color. To achieve this, I wrote an
AppSurface
Composable that wraps a regular surface, and sets the value of a
LocalButtonColor
composition local, and then wrote a
AppOutlinedButton
Composable that wraps a regular OutlinedButton, and sets it's color using the
LocalButtonColor
... Does this seem like the right approach? (Code is posted in the thread)
Copy code
val LocalButtonColor = compositionLocalOf { Color.Black }
private val buttonShape = RoundedCornerShape(50)


@Composable
fun AppSurface(
    modifier: Modifier = Modifier,
    shape: Shape = RectangleShape,
    color: Color = MaterialTheme.colors.surface,
    contentColor: Color = contentColorFor(color),
    border: BorderStroke? = null,
    elevation: Dp = 0.dp,
    content: @Composable () -> Unit
) {
    val buttonColor = when (color) {
        MaterialTheme.colors.surface -> MaterialTheme.colors.secondary
        MaterialTheme.colors.background -> MaterialTheme.colors.background
        else -> contentColor
    }

    CompositionLocalProvider(
        LocalButtonColor provides buttonColor
    ) {
        Surface(modifier, shape, color, contentColor, border, elevation, content)
    }
}

@Composable
fun AppOutlinedButton(
    text: String,
    onClick: ()->Unit = {},
    color: Color = LocalButtonColor.current
) {
    OutlinedButton(
        shape = buttonShape,
        border = BorderStroke(2.dp, color),
        colors = ButtonDefaults.outlinedButtonColors(backgroundColor = Color.Transparent, contentColor = color),
        onClick = onClick) {
        Text(text = text)
    }
}
it certainly seems to work ... I'm curious if this is a proper use case for CompositionLocal, and/or if there's any gotchas I haven't thought about.
s
This all looks like a correct usage to me
b
awesome, thanks @Sean McQuillan [G]