Skip to content

Instantly share code, notes, and snippets.

@lucas404x
Created June 29, 2022 10:15
Show Gist options
  • Save lucas404x/cc25c4f8314030ba5066c4bb4742da30 to your computer and use it in GitHub Desktop.
Save lucas404x/cc25c4f8314030ba5066c4bb4742da30 to your computer and use it in GitHub Desktop.
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