Home > Software design >  How Can I Handle State In Jetpack Compose?
How Can I Handle State In Jetpack Compose?

Time:08-27

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))
            }

        }

    }
}

CodePudding user response:

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

  • Related