Issue
We have the below compose which works well.
@Composable
fun MyInnerControl() {
var timerStartStop by remember { mutableStateOf(true) }
Button(onClick = {
timerStartStop = !timerStartStop
}) {
Text(if (timerStartStop) "Stop" else "Start")
}
}
But if we have the timerStartStop
passed through the function parameter, I cannot do as below
@Composable
fun MyInnerControl(timerStartStop: Boolean) {
Button(onClick = {
timerStartStop = !timerStartStop
}) {
Text(if (timerStartStop) "Stop" else "Start")
}
}
I can pass as below, but then I have to change my timerStartStop
to timerStartStop.value
@Composable
fun MyInnerControl(timerStartStop: MutableState<Boolean>) {
Button(onClick = {
timerStartStop.value = !timerStartStop.value
}) {
Text(if (timerStartStop.value) "Stop" else "Start")
}
}
Is there any way to have the MutableState<Boolean>
passed over the argument, yet within the function we can use the delegate approach, i.e. using timerStartStop
instead of timerStartStop.value
?
Solution
Jetpack Compose tells you to respect Single Source of Truth principle, which means that you can not pass state as argument if you want to change that state inside your function.
So generally you have to choose one of two approaches:
- Pass both timerStartStop variable and onClick callback
@Composable
fun MyInnerControl(timerStartStop: Boolean, onClick: ()->Unit) {
Button(onClick = onClick) {
Text(if (timerStartStop) "Stop" else "Start")
}
}
- Pass none of these
@Composable
fun MyInnerControl() {
var timerStartStop by remember { mutableStateOf(true) }
Button(onClick = {
timerStartStop = !timerStartStop
}) {
Text(if (timerStartStop) "Stop" else "Start")
}
}
Answered By - DemOn
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.