0

TextField always get empty when I try to write in it.

My ViewModel:

class MyVM: ViewModel() {
    var name by mutableStateOf("")

    fun onNameChange(newString: String) {
        name = newString
    }
}

In MainActivity:

val myVM = MyVM()

MyScreen(
    modifier = Modifier.fillMaxSize(),
    name = myVM.name
) {
    myVM.onNameChange(it)
}

MyScreen:

@Composable
fun MyScreen(
    modifier: Modifier,
    name: String,
    onNameChange: (String) -> Unit,
) {
    Box(
        modifier = modifier,
        contentAlignment = Alignment.Center,
    ) {
        OutlinedTextField(
            value = name,
            onValueChange = { newText -> onNameChange(newText) },
            label = { Text(text = "Name") },
            modifier = Modifier
                .fillMaxWidth()
                .padding(8.dp),
        )
    }
}

I want user to enter their name and in viewmodel update the name mutable state variable

1 Answer 1

3

Using val myVM = MyVM() in Compose will create a new view model instance on each recomposition, starting with a new name property that is empty.

You want the view model instance to survive recompositions. For that you need to use the factory function viewModel() like this:

val myVM = viewModel<MyVM>()

or

val myVM: MyVM = viewModel()

Take your pick.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.