Home > Blockchain >  Use of State hosting to change variable in jetpack compose
Use of State hosting to change variable in jetpack compose

Time:02-01

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() .

enter image description here

CodePudding user response:

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")
    }
}

CodePudding user response:

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")
    }
}
  • Related