fun TextFieldWithIconsAndErrorLabel(
text: String,
charLimit: Int = Int.MAX_VALUE,
keyboardType: KeyboardType = KeyboardType.Text,
onValueChange: (String) -> Unit,
) {
val keyboardController = LocalSoftwareKeyboardController.current
var shouldShowMaxCharLimitError by remember { mutableStateOf(false) }
BasicTextField(
modifier = Modifier
.fillMaxWidth(),
value = text,
onValueChange = { newInput ->
if (newInput.length > charLimit) {
shouldShowMaxCharLimitError = true
} else {
shouldShowMaxCharLimitError = false
onValueChange(newInput)
}
},
keyboardOptions = KeyboardOptions(
imeAction = ImeAction.Done,
keyboardType = keyboardType,
),
singleLine = true,
keyboardActions = KeyboardActions(
onDone = {
keyboardController?.hide()
onValueChange(text)
shouldShowMaxCharLimitError = false
}
),
)
if (shouldShowMaxCharLimitError) {
Text(
modifier = Modifier
.fillMaxWidth(),
text = "Max character limit exceeded",
style = TextStyle(
fontFamily = PoppinsFamily,
fontWeight = FontWeight.Medium,
fontSize = 12.sp,
color = Color.Red,
textAlign = TextAlign.Start
),
)
}
}
在上面的代码中,
onValueChange
被多次调用并立即重置布尔值。
对于每个文本输入,此 lambda 都会被调用两次。
onValueChange = { newInput ->
if (newInput.length > charLimit) {
shouldShowMaxCharLimitError = true
} else {
shouldShowMaxCharLimitError = false
onValueChange(newInput)
}
}
将 onValueChange 更改为此
onValueChange = { newInput ->
shouldShowMaxCharLimitError = newInput.length > charLimit
if (!shouldShowMaxCharLimitError) {
onValueChange(newInput)
}
}
并删除 onDone 回调中对 onValueChange(text) 的调用
onDone = {
keyboardController?.hide()
// Remove the following line
// onValueChange(text)
shouldShowMaxCharLimitError = false
}