Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How Can I Handle State In Jetpack Compose?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

   @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())

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading