Skip to content

Instantly share code, notes, and snippets.

@loicgeek
Last active June 26, 2020 16:25
Show Gist options
  • Save loicgeek/18e748e77c617037243740cf7136d20a to your computer and use it in GitHub Desktop.
Save loicgeek/18e748e77c617037243740cf7136d20a to your computer and use it in GitHub Desktop.
import 'package:flutter/services.dart';
import 'package:intl/intl.dart';
class CurrencyInputFormatter extends TextInputFormatter {
TextEditingValue formatEditUpdate(
TextEditingValue oldValue, TextEditingValue newValue) {
if (newValue.text.length == 0) {
return newValue.copyWith(text: '');
} else if (newValue.text.compareTo(oldValue.text) != 0) {
final f = new NumberFormat.currency(symbol: "\$ ", decimalDigits: 2);
int selectionIndexFromTheRight =
newValue.text.length - newValue.selection.end;
double num = double.parse(newValue.text
.replaceAll('\$ ', '')
.replaceAll(f.symbols.GROUP_SEP, ''));
final newString = f.format(num);
int intValue =
int.parse(intPart.substring(2).replaceAll(f.symbols.GROUP_SEP, ''));
int newoffset = newString.length - selectionIndexFromTheRight ;
return new TextEditingValue(
text: newString,
selection: TextSelection.collapsed(offset: newoffset),
);
} else {
return newValue;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment