Hi again, I was wondering why this code is not upd...
# compose
n
Hi again, I was wondering why this code is not updating the color of my buttons in real time. I'd be grateful for some pointers, thanks!
Copy code
val dynamicColor = remember { mutableStateOf(Color.Unspecified) }
            
            fun getDynamicColor(): Color {
                if (isEnabled)
                    when (callSender.value) {
                        0 -> dynamicColor.value = color3
                        1 -> dynamicColor.value = color1
                        2 -> dynamicColor.value = color2
                        3 -> dynamicColor.value = color0
                    } else dynamicColor.value = Color.DarkGray
                return dynamicColor.value
            }

            Button(modifier = Modifier.padding(10.dp).height(60.dp),
                elevation = ButtonDefaults.elevation(8.dp),
                colors = ButtonDefaults.buttonColors(
                    backgroundColor = getDynamicColor()
                ),
v
Assuming that
callSender
is another mutable state, you probably want to make
callSender.value
an argument of
getDynamicColor
and pass it at call site. That way changes in
callSender
will trigger the whole function re-evaluation and call for
getDynamicColor
as a result. The better solution would be using
derivedStateOf
for
dynamicColor
and put your mapping from
callSender.value
to color there.
n
Brilliant thanks, I'll look into
derivedStateOf
! 🙂