Hi! I have this function that returns a string in ...
# getting-started
g
Hi! I have this function that returns a string in this format: "1234567890-12345" i.e. it adds a hyphen after 10th string. but it has a weird bug; after adding the hyphen cursor stay there instead of going "in front of" the next typed digit. so cursor stays one character behind latest typed character. am i missing something here? i don't want to manually handle the position of the cursor. (i am using returned value in a textfield in compose)
Copy code
fun updateIdValue(type: Type, value: String = "") {
        val updatedValue = when (type) {
            
            Type.OBJECT ->{
                val cleanedValue = value.replace("-","")
                when {
                    cleanedValue.length < 10 -> cleanedValue
                    else -> {
                        val firstPart = cleanedValue.take(10)
                        val secondPart = cleanedValue.drop(10).take(5)
                        if (secondPart.isNotEmpty()) {
                            "$firstPart-$secondPart"
                        } else {
                            firstPart
                        }
                    }
                }
            }

            else -> value
        }

        _idValue.value = updatedValue
    }
e
the use of
.value
makes it appear you may be using
MutableStateFlow
, in which case: have you read https://medium.com/androiddevelopers/effective-state-management-for-textfield-in-compose-d6e5b070fbe5
Avoid using reactive streams (e.g.
StateFlow
) to represent your
TextField
state
g
@ephemient thanks for the source. i'm reading it now
e
in this case a digit-only
TextField
with a https://developer.android.com/reference/kotlin/androidx/compose/ui/text/input/VisualTransformation to insert the hyphen is what you should probably use
g
is there any alternative way here? i dont want to use visual tranformation because i was handling all the formatting in viewmodel function for all other types of this enum. writing all of them in ui screen wont look nice
a
.value
can also indicate a
MutableState
, ephemient. Gamar Mustafa, the visual transformation from docs gives an example of credit cards. Your use-case is similar.
🙌 1