Hi ! As a experiment and in order to understand wh...
# compose
l
Hi ! As a experiment and in order to understand why a part of my project does not work, I've created this ColorSquare experiment. 1. It is a simple `@Composable`which outputs a
Surface
with solid background color, and a
Button
. 2. When the user clicks on the button, the expected behaviour is that the square changes its color. 3. In this experiment, things are a bit more complicated : I'm using a
ColorSquareState
class, with a method
chooseNextColor
, and I'm storing a `mutableState`on an instance of this class. But when the `chooseNextColor`is called, it does not force recomposition. Why ? Is there a simple workaround keeping the use of `ColorSquareState`as long as method
chooseNextColor
?
o
The field you update should be backed by
State
. In your snippet the whole
ColorSquareState
is wrapped in the
State
and Compose are subscribed to it’s changes, but you are mutating the property inside
ColorSquareState
, which is not a
State
. So try the following: 1. Declare the property as
State
:
Copy code
var bgColor by mutableStateOf(blue)
2. Remove unnecessary
mutableStateOf
for the whole state:
Copy code
val color by remember { ColorSquareState() }
👍🏾 1
l
Thank you I'm gonna try now 🙂
Yes, it works. Thank you very much 🙂
👍 1