Changing the jetpack compose remember variable from within another function
Asked Answered
A

2

7

I am developing an application for android devices, using the jetpack compose library.

Example I created inside a compose function

var taskVeriable = remember {mutableStateOf("Hello World")}

I need to update the value of variable from another compose function. Is there any way to achieve this?

@Composable
fun TestComposeA(){

var taskVeriable = remember {mutableStateOf("Hello World")}

TestComposeB(taskVeriable)

}

@Composable
fun TestComposeB(taskVeriable : String){
taskVeriable = "New Value"
}

I want to know if there is a way to do this.

Aerodynamics answered 29/10, 2022 at 19:47 Comment(0)
S
10

You can pass mutable state and change it value later:

@Composable
fun TestComposeA(){

val taskVeriable = remember {mutableStateOf("Hello World")}

TestComposeB(taskVeriable)

}

@Composable
fun TestComposeB(taskVeriable : MutableState<String>){
taskVeriable.value = "New Value"
}
Sampler answered 30/10, 2022 at 16:56 Comment(0)
K
5

You can pass a function that changes your state. This might help you:

@Composable
fun CompA() {
    var text by remember { mutableStateOf("") }

    CompB(
        text = text,
        onChange = { newText ->
            text = newText
        }
    )
}

@Composable
fun CompB(
    text: String,
    onChange: (String) -> Unit
) {
    TextField(value = text, onValueChange = { onChange(it) })
}
Khorma answered 29/10, 2022 at 20:8 Comment(1)
This is the recommended way of doing this in Jetpack Compose as it follows the unidirectional data flow pattern.Chellman

© 2022 - 2024 — McMap. All rights reserved.