TextFiledData
Represents the state of a text input field with optional validation error.
This data class is designed to work within the UiState wrapper pattern, providing a clean way to manage text field state and validation errors. It's commonly used in screen data classes to represent form inputs.
Usage in Screen Data
data class LoginScreenData(
val email: TextFiledData = TextFiledData(""),
val password: TextFiledData = TextFiledData("")
)Content copied to clipboard
Usage in ViewModel
@HiltViewModel
class LoginViewModel @Inject constructor(
private val authRepository: AuthRepository
) : ViewModel() {
private val _uiState = MutableStateFlow(UiState(LoginScreenData()))
val uiState = _uiState.asStateFlow()
fun updateEmail(email: String) {
_uiState.updateState {
copy(email = TextFiledData(email, validateEmail(email)))
}
}
private fun validateEmail(email: String): String? {
return when {
email.isBlank() -> "Email cannot be empty"
!email.isValidEmail() -> "Invalid email format"
else -> null
}
}
}Content copied to clipboard
Usage in Composable
@Composable
fun LoginScreen(
screenData: LoginScreenData,
onEmailChange: (String) -> Unit
) {
OutlinedTextField(
value = screenData.email.value,
onValueChange = onEmailChange,
label = { Text("Email") },
isError = screenData.email.errorMessage != null,
supportingText = screenData.email.errorMessage?.let { { Text(it) } }
)
}Content copied to clipboard
With UiText for Type-Safe Errors
data class TextFiledData(
val value: String,
val errorMessage: UiText? = null // Use UiText instead of String
)
// In Composable:
supportingText = screenData.email.errorMessage?.let { error ->
{ Text(error.asString()) }
}Content copied to clipboard