Skip to content

Instantly share code, notes, and snippets.

@ArefMozafari
Last active February 22, 2021 12:43
Show Gist options
  • Save ArefMozafari/b553afdbcd44c71e5e0e35fe75494840 to your computer and use it in GitHub Desktop.
Save ArefMozafari/b553afdbcd44c71e5e0e35fe75494840 to your computer and use it in GitHub Desktop.
Flutter/Dart - How to add commas to a string number after each three digit
import 'package:flutter/services.dart';
import 'package:intl/intl.dart';
class NumericTextFormatter extends TextInputFormatter {
@override
TextEditingValue formatEditUpdate(
TextEditingValue oldValue, TextEditingValue newValue) {
if (newValue.text.isEmpty) {
return newValue.copyWith(text: '');
} else if (newValue.text.compareTo(oldValue.text) != 0) {
final int selectionIndexFromTheRight =
newValue.text.length - newValue.selection.end;
final f = NumberFormat("#,###");
final number =
int.parse(newValue.text.replaceAll(f.symbols.GROUP_SEP, ''));
final newString = f.format(number);
return TextEditingValue(
text: newString,
selection: TextSelection.collapsed(
offset: newString.length - selectionIndexFromTheRight),
);
} else {
return newValue;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment