TR4C3S 0F 45H
TR4C3S 0F 45H

Reputation: 75

How to fix OutlinedTextField value not changing?

I have an OutlinedTextField whose value is provided by a property in my ViewModel. However the value is not changing even after I type something on the keyboard of my physical device. The value always remains blank. I wonder what I'm doing wrong. Below is my code.

HouseEvent

sealed interface HouseEvent {
  data class OnDescriptionChanged(val description: String): HouseEvent
}

HouseViewModel

val house: House? by mutableStateOf(null)

fun onEvent(event: HouseEvent) {
  when(event) {
    is HouseState.OnDescriptionChanged -> {
      house = house.copy(
        description = event.description
      )
    }
  }
}

Navigation composable

val viewModel = viewModel<HouseViewModel>()

HouseEditScreen(
  house = viewModel.house, 
  onEvent = viewModel::onEvent
)

HouseEditScreen

@Composable
HouseEditScreen(
  house: House?, 
  onEvent: (HouseEvent) -> Unit
) {

  OutlinedTextField(
    value = house?.description ?: "",
    onValueChange = { description ->
      onEvent(HouseEvent.OnDescriptionChanged(description)
    }
  )

}

Using a MutableStateFlow approach works but it meant I had to redeclare every property in my House class in the House state file.

I expect the value of the OutlinedTextField to be updated as soon as I type something on the keyboard

Upvotes: 0

Views: 276

Answers (1)

Jan B&#237;na
Jan B&#237;na

Reputation: 7278

The house property in your ViewModel is declared as val, which means you cannot change it:

val house: House? by mutableStateOf(null)

which would result in a compilation error here:

house = house.copy(
    description = event.description
)

unless you have some other house variable there.

Upvotes: 2

Related Questions