Reputation: 9400
I have a compose button which has a @Model state.
@Model
class CounterState(var count: Int = 0)
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
MyApp {
Counter(CounterState())
}
}
}
}
@Composable
fun Counter(state: CounterState) {
Button(
text = "I've been clicked ${state.count} times",
onClick = {
state.count++
},
style = ContainedButtonStyle(color = if (state.count > 5) Color.Green else Color.White)
)
}
when I click button it's text is not updated.
Does anyone know why?
Upvotes: 2
Views: 667
Reputation: 20187
On this line
Counter(CounterState())
you're creating a new CounterState
every time, which resets it to zero every time it's recomposed. You should create it once, outside of the composition, and then store it in a variable to pass into Counter
each time.
Upvotes: 1