0

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()
        }

    }
}

1 Answers1

0

You can do it this way:

Create variable inside your composable

var workoutTitle = remember{mutableStateOf("")}

Pass your variable value in your textfield:

  TextField(
                value = workoutTitle.value,
                onValueChange = {
                    /* You can store the value of your text view inside your
                    view model maybe as livedata object or state anything which suits you
                   */
                }
            )
Arsh
  • 279
  • 2
  • 6