简体   繁体   中英

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:

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

        }

    }
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM