MutableStyleState

Class
Common
@ExperimentalFoundationStyleApi
class MutableStyleState
@RememberInComposition
constructor(override val interactionSource: InteractionSource?) : StyleState()

The state a style that can be updated to reflect the current state of a component. This value should be created in a component and updated to select the style parameter to be set for the component.

A component that uses an interaction source can create a MutableStyleState that observes the interactions emitted to the interaction source.

Functions

operator fun <T> set(key: StyleStateKey<T>, value: T)

Set the value of the key in the StyleState.

fun <T> remove(key: StyleStateKey<T>)

Removes the StyleStateKey from the StyleState.

A Style will read the StyleStateKey.defaultValue for the StyleStateKey when the key is not present in the StyleState.

Removing a key that is updated via an InteractionSource will no longer observe the interaction source.

Predefined style keys, such as StyleStateKey.Pressed and StyleStateKey.Hovered, cannot be removed from the set of keys and this will throw if removed.

Code Examples

StyleStateSample

@Composable
fun StyleStateSample() {
    // Create a styleable clickable box
    @Composable
    fun ClickableStyleableBox(
        onClick: () -> Unit,
        modifier: Modifier = Modifier,
        style: Style = Style,
        enabled: Boolean = true,
    ) {
        val interactionSource = remember { MutableInteractionSource() }
        val styleState = rememberUpdatedStyleState(interactionSource) { it.isEnabled = enabled }
        Box(
            modifier =
                modifier
                    .clickable(interactionSource = interactionSource, onClick = onClick)
                    .styleable(styleState, style)
        )
    }
    // Create a 150x150 green box that is clickable
    ClickableStyleableBox(
        onClick = {},
        style = {
            background(Color.Green)
            size(150.dp)
            hovered { background(Color.Yellow) }
            pressed { background(Color.Red) }
            disabled { background(Color.Gray) }
        },
    )
}