Skip to content

Instantly share code, notes, and snippets.

@m-kikuchi777
Last active December 5, 2022 11:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save m-kikuchi777/af7ba8eee3e340a5776e243a82cb394f to your computer and use it in GitHub Desktop.
Save m-kikuchi777/af7ba8eee3e340a5776e243a82cb394f to your computer and use it in GitHub Desktop.
3桁ごとにカンマ区切りを入れるTextInputFormatter
class NumberTextInputFormatter extends TextInputFormatter {
final _exceptNumberAndComma = RegExp(r'[^0-9,]+');
final _numberFormatter = NumberFormat('#,###');
@override
TextEditingValue formatEditUpdate(
TextEditingValue oldValue,
TextEditingValue newValue,
) {
if (newValue.text.isEmpty) {
return newValue;
}
if (_exceptNumberAndComma.hasMatch(newValue.text)) {
return oldValue;
}
final isDeleted = newValue.text.length - oldValue.text.length < 0;
final String adjustedText;
if (isDeleted) {
final isCommaDeleted = oldValue.text.substring(
newValue.selection.extentOffset,
oldValue.selection.extentOffset,
) ==
',';
if (isCommaDeleted) {
adjustedText = newValue.text.replaceRange(
newValue.selection.extentOffset - 1,
newValue.selection.extentOffset,
'',
);
} else {
adjustedText = newValue.text;
}
} else {
adjustedText = newValue.text;
}
final int value;
try {
value = int.parse(adjustedText.replaceAll(',', ''));
} on FormatException {
return oldValue;
}
final formattedText = _numberFormatter.format(value);
final selection = newValue.selection.extentOffset +
formattedText.length -
newValue.text.length;
return newValue.copyWith(
text: formattedText,
selection: TextSelection.collapsed(offset: selection < 0 ? 0 : selection),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment