fix: crash when editing int or long values#338
Conversation
There was a problem hiding this comment.
Pull Request Overview
This PR fixes a crash that occurred when editing integer or long values in the editor by implementing proper input validation and state management. The crash was likely caused by attempting to convert invalid input strings directly to numeric types without proper error handling.
Key Changes:
- Added local state management (
inputValue) to track user input separately from validated output - Implemented safe type conversion using
toIntOrNull()andtoLongOrNull()to prevent crashes on invalid input - Applied consistent input handling pattern across Int, Long, and String value types
Tip: Customize your code reviews with copilot-instructions.md. Create the file or learn how to get started.
|
|
||
| @Composable | ||
| fun SingleValueEditor(data: DataRow, onValueChange: (String) -> Unit) { | ||
| var inputValue by remember { mutableStateOf(data.value ?: "") } |
There was a problem hiding this comment.
The inputValue state is not keyed to data, which means it won't update when data changes (e.g., when navigating between different rows). Consider using remember(data.value) or rememberSaveable(data.value) to ensure the state resets when the data source changes.
| var inputValue by remember { mutableStateOf(data.value ?: "") } | |
| var inputValue by remember(data.value) { mutableStateOf(data.value ?: "") } |
| onValueChange = { newInput -> | ||
| inputValue = newInput | ||
| newInput.toIntOrNull()?.let { onValueChange(it.toString()) } | ||
| }, |
There was a problem hiding this comment.
When the user enters invalid input (e.g., non-numeric characters), toIntOrNull() returns null and onValueChange is not called. This means the local inputValue is updated but the parent state is not, potentially causing inconsistency. Consider providing feedback to the user or clearing invalid input.
| TextField( | ||
| value = inputValue, | ||
| onValueChange = { newInput -> | ||
| inputValue = newInput | ||
| newInput.toIntOrNull()?.let { onValueChange(it.toString()) } | ||
| }, | ||
| keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number), | ||
| modifier = Modifier.fillMaxWidth(), | ||
| ) | ||
| } | ||
| is Long -> { | ||
| TextField( | ||
| value = inputValue, | ||
| onValueChange = { newInput -> | ||
| inputValue = newInput | ||
| newInput.toLongOrNull()?.let { onValueChange(it.toString()) } | ||
| }, | ||
| keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number), | ||
| modifier = Modifier.fillMaxWidth(), | ||
| ) |
There was a problem hiding this comment.
When the user enters invalid input (e.g., non-numeric characters), toLongOrNull() returns null and onValueChange is not called. This means the local inputValue is updated but the parent state is not, potentially causing inconsistency. Consider providing feedback to the user or clearing invalid input.
No description provided.