Home > Software engineering >  State doesn't update
State doesn't update

Time:09-01

My state doesn't update if I call the function: flipButtonClicked() Does someone know why?

class FlipCardViewModel(cardState: CardState): ViewModel() {
private var _state by mutableStateOf(
    cardState
)

val state: CardState
    get() = _state

fun flipButtonClicked(){
    _state.isFlipped = !_state.isFlipped
}}

CodePudding user response:

You need to assign new instance to _state, changing property of an Object doesn't trigger recomposition by default.

If your CardState is a data class you can do it as

fun flipButtonClicked(){
    _state = _state.copy(!_state.isFlipped)
}}

CodePudding user response:

Ma' man your state don't update cuz' you didn't do no reading of the docs.

Just initialise the state variable like

var state by mutableStateOf(cardState)

and update it like

state = state.copy(!state.isFlipped)

Why add unnecessary complicated third party calls?

EDIT: Localised accent is devoted to the "Original" Post by the author, before someone decided to edit it out to localise it for "themselves".

  • Related