Compose Text Field strange behaviour when setting a max length for text

Viewed 1201

I am trying to set a limit for the max characters count in a TextField. This is what I tried:

var text by remember { mutableStateOf("") }
val maxLength = 40
TextField(
    value = text,
    onValueChange = {
        text = it.take(maxLength)
    }
)

Here's the problem:

  • When I exceed the limit, the entire text suddenly gets cleared.
  • This happens only once i.e. when I retype and exceed limit it just stops there (which is the desired behavior)
  • 40 seems like a magic number here, because for maxLength = 39 or lower, everything works fine. When I set the limit to 40 or higher, I see this strange behavior. (This magic number doesn't seem to depend upon text field width as I experimented with both portrait and landscape mode and the result was same)

How to get rid of this behavior? What's the right way to set a max length for TextField text?

enter image description here

2 Answers

You should not use take() to limit the number of strings.

take() only means to take the first number of strings.

You can consider the string itself, and just judge the number of strings so that it does not exceed 40.

var text by remember { mutableStateOf("") }
val maxLength = 40
TextField(
    value = text,
    onValueChange = {
        if (it.length <= 40)
          text = it
    }
)

I noticed that this bug doesn't occur on Android 12, where on 11 and lower it does.

Fortunately, according to Google Issue Tracker, that was a TextField bug that it is already fixed in Jetpack Compose 1.2.0-alpha04.

See related topics here and here.

Related