Description:
It's pretty basic problem but I've tried few solutions and nothing is working for me. I simply want to save state of BasicTextField in ViewModel. I tried mutableStateOf("SampleText") and text appears in BasicTextField but is not editable, even keyboard didn't appear.
ViewModel Code:
@HiltViewModel
class NewWorkoutViewModel @Inject constructor(...) : ViewModel() {
var workoutTitle by mutableStateOf("")
...
}
Screen Code:
@Composable
fun NewWorkoutScreen(
navController: NavController,
viewModel: NewWorkoutViewModel = hiltViewModel()
) {
Scaffold(...) { contentPadding ->
LazyColumn(...) {
item {
FillInContentBox(title = "Title:") {
// TextField which is not working
BasicTextField(textStyle = TextStyle(fontSize = 20.sp),
value = viewModel.workoutTitle,
onValueChange ={viewModel.workoutTitle = it})
}
}
}
}
}
@Composable
fun FillInContentBox(title: String = "", content: @Composable () -> Unit = {}) {
Box(...) {
Column(...) {
Text(text = title)
content()
}
}
}
Second attempt:
I tried also using State Flow but still, I can't edit (fill in) text into TextField.
ViewModel Code:
@HiltViewModel
class NewWorkoutViewModel @Inject constructor(...) : ViewModel() {
private val _workoutTitle = MutableStateFlow("")
var workoutTitle = _workoutTitle.asStateFlow()
fun setWorkoutTitle(workoutTitle: String){
_workoutTitle.value = workoutTitle
}
...
}
Screen Code:
@Composable
fun NewWorkoutScreen(
navController: NavController,
viewModel: NewWorkoutViewModel = hiltViewModel()
) {
Scaffold(...) { contentPadding ->
LazyColumn(...) {
item {
FillInContentBox(title = "Title:") {
// TextField which is not working
BasicTextField(textStyle = TextStyle(fontSize = 20.sp),
value = viewModel.workoutTitle.collectAsState().value,
onValueChange = viewModel::setWorkoutTitle)
}
}
}
}
}
@Composable
fun FillInContentBox(title: String = "", content: @Composable () -> Unit = {}) {
Box(...) {
Column(...) {
Text(text = title)
content()
}
}
}