Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Use of State hosting to change variable in jetpack compose

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

@Composable
fun ButtonScopeStateless(
    index: () -> Int,
    onIndexChange: (Int) -> Unit,
) {
    Button(onClick = { onIndexChange(index()++) }) {
        Text(text = "Click Me $index")
    }
}

I am getting error on index()++.

enter image description here

>Solution :

Using the general pattern for state hoisting your stateless composable should have two parameters:

  • value: T: the current value to display
  • onValueChange: (T) -> Unit: an event that requests the value to change, where T is the proposed new value

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")
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading