Input errors - Jetpack Compose
In Jetpack Compose, you can use error
function inside the semantics
block modifier to announce an error message to the accessibility service. Keep in mind that these announcements will not be shown visually. To show the message, use label
property of TextField
in conjunction with isError
, which automatically changes the appearance of the TextField
.
var errorMessage by remember { mutableStateOf("") }
val isError = remember(errorMessage) { errorMessage.isNotEmpty() }
TextField(
value = "",
label = {
Text(errorMessage.ifEmpty { "TextField label" })
},
isError = isError,
onValueChange = { /* State update logic */ },
modifier = Modifier
.semantics {
if (errorMessage.isNotEmpty()) {
error(errorMessage)
}
}
)
Important: Check if the import androidx.compose.ui.semantics.error
is present when using the error
function; otherwise, Kotlin will use the standard error
function, which throws an IllegalStateException
with your message.