Home > Software engineering >  How to assign value in setter of mutableStateOf in kotlin
How to assign value in setter of mutableStateOf in kotlin

Time:08-24

I am working in mutableStateOf. I want to assign value when initialise the variable. I have one string value which I want to assign in mutableStateOf. When string is empty then I don't want to set any value in my mutableStateOf variable. I am trying but getting error.

val answer: String? = null

var textFieldValue = mutableStateOf(TextFieldValue())
        set(value) {
            field = value
            if(!answer.isNullOrEmpty()){
                field = answer
            }
        }

I am getting error

Type mismatch.
Required: MutableState<TextFieldValue>
Found: String

I want to set TextFieldValue() when my answer is null. Many Thanks

CodePudding user response:

This should work,

val answer: String? = null
var textFieldValue = mutableStateOf(TextFieldValue(answer ?: ""))
  • Related