Last active
June 4, 2025 10:02
-
-
Save rubywai/376bcb7d068797cd7316e275082a8df3 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 StrictRangeFilteringTextInputFormatter extends FilteringTextInputFormatter { | |
final double min; | |
final double max; | |
final bool allowNegative; | |
final bool unlimitedDecimals; | |
final int? decimalPlaces; | |
StrictRangeFilteringTextInputFormatter({ | |
required this.min, | |
required this.max, | |
this.allowNegative = false, | |
this.unlimitedDecimals = false, | |
this.decimalPlaces, | |
}) : super.allow(_buildRegExp(allowNegative, decimalPlaces, unlimitedDecimals)); | |
static RegExp _buildRegExp(bool allowNegative, int? decimalPlaces, bool unlimitedDecimals) { | |
final sign = allowNegative ? '-?' : ''; | |
final decimal = unlimitedDecimals | |
? '(\\.\\d*)?' | |
: (decimalPlaces != null && decimalPlaces > 0 | |
? '(\\.\\d{0,$decimalPlaces})?' | |
: ''); | |
final pattern = '^$sign\\d*$decimal\$'; | |
return RegExp(pattern); | |
} | |
@override | |
TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) { | |
final filtered = super.formatEditUpdate(oldValue, newValue); | |
final text = filtered.text; | |
// Allow partial input like "-", ".", "-." | |
if (text.isEmpty || text == '-' || text == '.' || text == '-.') { | |
return filtered; | |
} | |
final number = double.tryParse(text); | |
if (number == null || number < min || number > max) { | |
return oldValue; | |
} | |
return filtered; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment