0
votes

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?

1

1 Answers

0
votes

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.