Created
June 29, 2022 10:15
-
-
Save lucas404x/cc25c4f8314030ba5066c4bb4742da30 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class QuantityInputFormatter extends TextInputFormatter { | |
@override | |
TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) { | |
if (newValue.text.isEmpty) { | |
return const TextEditingValue( | |
text: '0', | |
selection: TextSelection.collapsed(offset: 1), | |
); | |
} | |
final validValue = _isInteger(newValue.text) ? _convertToValidIntegerFormat(newValue.text) : _convertToValidFloatFormat(newValue.text); | |
return TextEditingValue( | |
text: validValue, | |
selection: TextSelection.collapsed(offset: validValue.length), | |
); | |
} | |
bool _isInteger(String value) { | |
return !value.contains('.') && !value.contains(','); | |
} | |
String _convertToValidIntegerFormat(String value) { | |
if (value.length > 1 && value[0] == '0') { | |
return value.replaceFirst('0', ''); | |
} | |
return value; | |
} | |
String _convertToValidFloatFormat(String value) { | |
final tmp = value.replaceAll(',', '.').split('.'); | |
tmp.insert(1, '.'); | |
return tmp.join(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment