I have a root layout of a Box with a background co...
# compose
c
I have a root layout of a Box with a background color, but I want the background color to animate in after delaying like 300ms. What's the easiest anim apis to do something like that?
f
depends on whether you want this to be a one off or if you want to have more fine grained control. This is one possible way to go about it
Copy code
@Composable
fun AnimatedBox(
    modifier: Modifier = Modifier,
    startColor: Color = Color.Transparent,
    endColor: Color = MaterialTheme.colorScheme.primary,
) {
    var trigger by remember {
        mutableStateOf(false)
    }
    val color by animateColorAsState(
        targetValue = if (trigger) endColor else startColor,
        animationSpec = tween(
            durationMillis = 1000,
            delayMillis = 300
        )
    )
    LaunchedEffect(key1 = Unit) {
        trigger = true
    }
    Box(
        modifier = modifier.background(color)
    )
}
if you just want to animate the alpha in, this is another option
Copy code
@Composable
fun AnimatedBox(
    modifier: Modifier = Modifier,
    color: Color = MaterialTheme.colorScheme.primary,
) {
    val animatable = remember { Animatable(0f) }
    LaunchedEffect(key1 = Unit) {
        animatable.animateTo(
            targetValue = 1f,
            animationSpec = tween(
                durationMillis = 1000,
                delayMillis = 300
            ),
        )
    }
    Box(
        modifier = modifier.graphicsLayer {
            alpha = animatable.value
        }.background(color)
    )
}
you could also use
animateFloatAsState
to animate the alpha value using a trigger like in the 1st example, there are multiple ways to skin this cat
s
Copy code
val whatever by produceState(initialValue) {
    animate(initialValue, targetValue, animationSpec = tween(delayMillis = 300)) { value, _ ->
        this.value = value
    }
}
If you need a spring (or another animation spec that doesn't support delaying), you can just call
delay(300
before
animae(...)