Last active
June 26, 2020 16:25
-
-
Save loicgeek/18e748e77c617037243740cf7136d20a 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
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