Hi guys, I want to change the value of variable in...
# compose
k
Hi guys, 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
Copy code
@Composable
fun ItemColorStateful() {
    var index by remember { mutableStateOf(-1) }
    Column(modifier = Modifier.fillMaxSize()) {
        Text(text = "Different Color")
        ButtonScopeStateless(
            index = { index },
            onIndexChange = {
                index = it
            }
        )
    }
}
ButtonScopeStateless
Copy code
@Composable
fun ButtonScopeStateless(
    index: () -> Int,
    onIndexChange: (Int) -> Unit,
) {
    Button(onClick = { onIndexChange(index()++) }) {
        Text(text = "Click Me $index")
    }
}
Screenshot 2023-02-01 at 11.14.58.png
s
Do
index() + 1
. You can’t increment a parameter which is immutable, as that’s what
++
is trying to do.
k
Perfect thanks for gudiance
@Stylianos Gakis another question, In
ButtonScopeStateless
on the first parameter should I use
index: () -> Int,
or
index: Int
. Which one is good in my conditon?
s
For correctness, it’s the same. For performance, the () -> Unit may be better, but it really depends if you even have a problem in the first place. I’d recommend reading this as a starter to understand what you are optimizing for. Then also read this. Once both of these make 100% sense to you consider going with the lambda implementation in the places where you identify that this is needed. Otherwise just use the simple style until you can make these decisions for yourself. That’s how I’d start personally.
k
Thank you so much for sharing great articles...