I am trying to achieve the requirement that my TextField can only accept 10 digits, and I have used 'rememberSaveable' so that when the user navigates to another screen and then comes back to this screen, the digits entered in TextField isn't lost.
I have used rememberSaveable like:
var query by rememberSaveable { mutableStateOf(TextFieldValue("")) }
Then I used it in my TextField as:
val maxChar = 10
TextField(
value = query,
onValueChange = {
if (it.text.length <= maxChar) query = it
},
label = {
Text(
"Name as on PAN Card",
color = colorResource(id = R.color.bright_green),
fontSize = with(LocalDensity.current) { dimensionResource(id = R.dimen._12ssp).toSp() },
fontFamily = FontFamily(Font(R.font.poppins_regular)),
textAlign = TextAlign.Left
)
},
interactionSource = interactionSource,
keyboardOptions = KeyboardOptions(keyboardType =KeyboardType.Number),
textStyle = TextStyle(
textAlign = TextAlign.Start,
color = colorResource(id = R.color.bright_green),
fontFamily = FontFamily(Font(R.font.poppins_regular)),
fontSize = with(LocalDensity.current) { dimensionResource(id = R.dimen._12ssp).toSp() }
),
modifier = Modifier
.drawBehind {
val strokeWidth = indicatorWidth.value * density
val y = size.height - strokeWidth / 2
drawLine(
indicatorColor,
Offset(TextFieldPadding.toPx(), y),
Offset(size.width - TextFieldPadding.toPx(), y),
strokeWidth
)
}
.constrainAs(name) {
bottom.linkTo(glNameBottom)
start.linkTo(glLeft)
end.linkTo(glRight)
width = Dimension.fillToConstraints
}
.height((mHeight.value / 10.5).dp),
colors = TextFieldDefaults.textFieldColors(
backgroundColor = Color.Transparent,
cursorColor = colorResource(id = R.color.bright_green),
focusedIndicatorColor = Transparent,
unfocusedIndicatorColor = Transparent,
disabledIndicatorColor = Transparent
)
)
But on using the above code I'm getting the exception:
java.lang.IllegalArgumentException: MutableState containing TextFieldValue(text='', selection=TextRange(0, 0), composition=null) cannot be saved using the current SaveableStateRegistry. The default implementation only supports types which can be stored inside the Bundle. Please consider implementing a custom Saver for this class and pass it as a stateSaver parameter to rememberSaveable().
How do I solve this?
As suggested on the documentation for the BasicTextField, you can simply use the TextFieldValue.Saver:
var query by rememberSaveable(stateSaver = TextFieldValue.Saver) { mutableStateOf(TextFieldValue("")) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With