Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

497
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda