Reputation: 7271
I want to change the value of variable in jetpack compose. I am trying to use Stateful
and Stateless
with some code, but it have some problem to increment the value. Can you guys guide me on this.
ItemColorStateful
@Composable
fun ItemColorStateful() {
var index by remember { mutableStateOf(-1) }
Column(modifier = Modifier.fillMaxSize()) {
Text(text = "Different Color")
ButtonScopeStateless(
index = { index },
onIndexChange = {
index = it
}
)
}
}
ButtonScopeStateless
@Composable
fun ButtonScopeStateless(
index: () -> Int,
onIndexChange: (Int) -> Unit,
) {
Button(onClick = { onIndexChange(index()++) }) {
Text(text = "Click Me $index")
}
}
I am getting error on index()++
.
Upvotes: 2
Views: 1907
Reputation: 364441
Using the general pattern for state hoisting your stateless composable should have two parameters:
In your case:
index: Int
,onIndexChange: (Int) -> Unit
Also you should respect the Encapsulated properties: Only stateful composables can modify their state. It's completely internal.
Use onIndexChange(index+1)
instead of onIndexChange(index()++)
. In this way the state is modified by the ItemColorStateful
.
You can use:
@Composable
fun ItemColorStateful() {
var index by remember { mutableStateOf(-1) }
Column(modifier = Modifier.fillMaxSize()) {
Text(text = "Different Color")
ButtonScopeStateless(
index = index ,
onIndexChange = {
index = it
}
)
}
}
@Composable
fun ButtonScopeStateless(
index: Int, //value=the current value to display
onIndexChange: (Int) -> Unit //an event that requests the value to change, where Int is the proposed new value
) {
Button(onClick = { onIndexChange(index+1) }) {
Text(text = "Click Me $index")
}
}
Upvotes: 2
Reputation: 1491
ItemColorStateful
@Composable
fun ItemColorStateful() {
var index by remember { mutableStateOf(-1) }
Column(modifier = Modifier.fillMaxSize()) {
Text(text = "Different Color")
ButtonScopeStateless(
index = index ,
onIndexChange = {
index++
}
)
}
}
ButtonScopeStateless
@Composable
fun ButtonScopeStateless(
index: Int,
onIndexChange: () -> Unit,
) {
Button(onClick = {
onIndexChange()
}) {
Text(text = "Click Me $index")
}
}
Upvotes: 0