How This Occurred
- When validating inputs, I used
.toInt()to convert a String to an Int but when the String was empty or contained characters that were non-numeric, it caused the IntParse Error - When I used
.toInt()on a String containing only numeric values but was too long for an Int, it would throw the IntParse Error also
How I Fixed It
- Using
.toIntOrNull() ?: 0( replacing 0 with the fallback value to be used if null ) instead of.toInt() - Enforcing a max length on the input that the user can NOT exceed
- Enforcing 0 as a default value for a numeric InputField so it’s never empty
Update
By Enforcing that the output of the IntInputField() composable was always numerical, I was able to revert any .toIntOrNull() statements back to .toInt() and then I applied this as soon as the variable is update rather then when using it to check validity. This meant I also had to convert the variable back to a string when passing it into the IntInputField() using .toString()
var startingChips by remember { mutableIntStateOf(1000) }
val startingChipsValid by remember {
derivedStateOf {
startingChips in bigBlind * 10 .. 1000000
}
}
IntInputField(
label = "Starting Chips",
initialValue = startingChips.toString(),
maxLen = 6,
isValid = startingChipsValid,
onValueChange = { startingChips = it.toInt() },
modifier = Modifier.width(240.dp)
)