Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

dart - Flutter: Using NumberFormat in TextInputFormatter

I'm trying to use NumberFromatter in TextInputFormatter but when I try to use it, it completely messed up! This is my TextInputFormatter implementation code:

class NumericTextFormatter extends TextInputFormatter {
  TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) {
    if(newValue.text.length > 0) {
      int num = int.parse(newValue.text.replaceAll(',', ''));
      final f = new NumberFormat("#,###");
      return newValue.copyWith(text: f.format(num));
    } else { 
      return newValue.copyWith(text: '');
    }
  }
}

So when I add this formatter to a TextField and try to type 1 to 9, what I expect to see is something like: 123,456,789

But this is what shows in TextField:

1
12
123
1,234
12,354 <- this is where it starts
123,564
1,235,674
12,356,874 <- and it happends again

It seems that cursor moves after adding one , character. So can anyone helps me with this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This is because after you format the value you are adding a new char but the text selection remains at the same position, one char less, this cause an expected behavior

You can modify your TextInputFormatter like this:

Fixed to support all locales and to remember cursor position

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;
    }
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...