简体   繁体   中英

How to update composable state from outside?

For example it working with state{} within composable function.

@Composable
fun CounterButton(text: String) {
    val count = state { 0 }

    Button(
        modifier = Modifier.padding(8.dp),
        onClick = { count.value++ }) {
        Text(text = "$text ${count.value}")
    }
}

But how to update value outside of composable function? I found a mutableStateOf() function and MutableState interface which can be created outside composable function, but no effect after value update.

Not working example of my attempts:

private val timerState = mutableStateOf("no value", StructurallyEqual)

@Composable
private fun TimerUi() {
    Button(onClick = presenter::onTimerButtonClick) {
        Text(text = "Timer Button")
    }
    Text(text = timerState.value)
}

override fun updateTime(time: String) {
    timerState.value = time
}

Compose version is 0.1.0-dev14

You can do it by exposing the state through a parameter of the controlled composable function and instantiate it externally from the controlling composable.

Instead of:

@Composable
fun CounterButton(text: String) {
     val count = remember { mutableStateOf(0) }
     //....
 }

You can do something like:

@Composable
fun screen() {

    val counter = remember { mutableStateOf(0) }

    Column {
        CounterButton(
            text = "Click count:",
            count = counter.value,
            updateCount = { newCount ->
                counter.value = newCount
            }
        )
    }
}

@Composable
fun CounterButton(text: String, count: Int, updateCount: (Int) -> Unit) {
    Button(onClick = { updateCount(count+1) }) {
        Text(text = "$text ${count}")
    }
}

In this way you can make internal state controllable by the function that called it.
It is called state hoisting .

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