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
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.
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"