How Can I Handle State In Jetpack Compose?

Issue

I try to change the value of a card with a slider, but it won’t work. The slider is not movable and the value in the card don’t change. Do you have an idea what I’m doing wrong?

View Model:

class CardSelectionViewModel: ViewModel() {
private var _state by mutableStateOf(
    CardState()
)
val state: CardState
    get() = _state

fun setCardValue(value: Float){
    CardState().value = (Math.round(value * 2) / 2.0).toFloat()
}
}
data class CardState(
var value: Float = 0f
)

View:

   @Composable
   fun CardSelectionScreen(state: CardState) {
    val viewModel = CardSelectionViewModel()
    CardSelectionScreenTheme {
        Column(
            verticalArrangement = Arrangement.Center,
            horizontalAlignment = Alignment.CenterHorizontally,
            modifier = Modifier.fillMaxSize()
        ) {
            CardContent(remember{viewModel.state.value})
            Slider(
                value = viewModel.state.value,
                onValueChange = {
                    viewModel.setCardValue(it)
                },
                valueRange = 0f..7f,
                modifier = Modifier.width(300.dp)
            )
            Button(onClick = {
                state.value ++
                println(state.value) }) {
                Text(text = stringResource(R.string.Continue))
            }

        }

    }
}

Solution

You are creating new instance of CardState() inside setCardValue instead of setting _state = CardState((Math.round(value * 2) / 2.0).toFloat())

Answered By – Thracian

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published