Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

494
Visualizações
How can i change value in TextField value from viewModel in jetpack compose

I am using jetpack compose in my project, and don't know how to change 'TextFile' value from viewmodel.

in my activity:

...
@Composable
fun myview(){
  var dname = remember {
          mutableStateOf(TextFieldValue(""))
      }
  TextField(value = dname.value, 
      onValueChange = { dname.value = it }, 
      modifier =Modifier.fillMaxWidth()
  )
}
...

in my viewmodel:

...
var dname = MutableStateFlow("")
...

I want to call dname.value="test" in viewmodel and change the shown value in TextField

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

Assuming you have a reference to your viewModel called viewModel, you just have to call viewModel.name.collectAsState(). But beyond that, I suggest keeping the data logic in the ViewModel, by making the MutableStateFlow private and exposing an immutable StateFlow and a setter method to the composable.

// ViewModel
private val _name = MutableStateFlow("")
val name = _name.asStateFlow()

fun setName(name: String) {
  _name.value = name
}
// Composable
val name = viewModel.name.collectAsState()
TextField(
  value = name,
  onValueChange = viewModel::setName
)

As you can see, I'm not using remember { mutableStateOf(...) } here, because the StateFlow in the ViewModel is the single source of truth.

Your approach of setting the composable's value imperatively doesn't make sense in the declarative API that Jetpack Compose provides.

Try reading up on declarative/imperative UI and state in Jetpack compose as well as kotlin flow to learn more.

over 4 years ago · Santiago Trujillo Relatório

0

You can also use mutableStateOf instead of MutableStateFlow. I think it much simple.

ViewModel

var dname by mutableStateOf("init value")

Composable

TextField(
    value = viewModel.dname,
    onValueChange = { viewModel.dname = it }
)

In ViewModel, when you want to change the value, you can call dname = "test"

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda