简体   繁体   中英

I get “Type mismatch. Required: State<String?> Found: String” when Using viewModel.observeAsState() with Jetpack compose

I am creating an app that takes users input in a textfield and instead of using:

var textState = remember { mutableStateOf("") }

I opted for using viewModels like

var title : State<String?> = addTaskViewModel.title.observeAsState()

TextField(
modifier = Modifier.fillMaxWidth(),
value = title.value!!,
onValueChange = { title = it },
shape = textFieldShape,
colors = textFieldColors,
label = {Text("Add a title",)} )

I get an error

Type mismatch. Required: State<String?> Found: String

when setting onValueChange = { title = it } on the TextField widget.

How can I use viewModel.observeAsState() with a TextField?

The best way is to create inside the ViewModel class a function to change this value.

Something like:

class TaskViewModel : ViewModel() {

    //Just an example
    private var _title = MutableLiveData("")
    var title: LiveData<String> = _title

    fun onTitleChange(newName: String) {
        _title.value = newName
    }
}

and then:

val title : State<String> = taskViewModel.title.observeAsState("")
TextField(
        modifier = Modifier.fillMaxWidth(),
        value = title.value,
        onValueChange = { taskViewModel.onTitleChange(it) },
        label = {Text("Add a title")} )

or:

  val title: String by taskViewModel.title.observeAsState("")
  TextField(
        modifier = Modifier.fillMaxWidth(),
        value = title,
        onValueChange = { taskViewModel.onTitleChange(it) },
        label = {Text("Add a title")} )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM