Home > Back-end >  How to format text inside text field?
How to format text inside text field?

Time:06-01

I want to format the text in the textfield according to the pattern: "х,ххх.хх", where every three orders a comma will be placed, and after the point there should be no more than two characters. For setting commas I have a controller:

    myController.addListener(() {
        String text = (myController.text).replaceAllMapped(RegExp(r'(\d{1,3})(?=(\d{3}) (?!\d))'), (Match m) => '${m[1]},');
  myController.value = myController.value.copyWith(
    text: text,
    selection:
        TextSelection(baseOffset: text.length, extentOffset: text.length),
    composing: TextRange.empty,
  );
});

To prevent entering two points in a row and more than two characters after the dot I have input formatters:

                         inputFormatters:[
  FilteringTextInputFormatter.allow(RegExp("[0-9.]")),
  FilteringTextInputFormatter.deny(RegExp(r"\.\.")),
  FilteringTextInputFormatter.deny(RegExp(r"\....")),

],

They certainly work, but not in the way I need. If the user enters two points in a row, then both will simply be deleted from him. And if you enter the third digit after the point, then the entire fractional part will be deleted altogether.

CodePudding user response:

You can use the NumberFormatter for formatting string.

Example :

import 'package:intl/intl.dart';

void main() {
  var formatter = NumberFormat('#,##,000');
  print(formatter.format(12345));
  print(formatter.format(67890));
  print(formatter.format(123456));
}

Output :

12,345
67,890
1,23,456

CodePudding user response:

I solved the problem with TextInputFormatter.withFunction:

                        inputFormatters: [
                      FilteringTextInputFormatter.allow(RegExp("[0-9.]")),
                      TextInputFormatter.withFunction((oldValue, newValue) {
                        RegExp reg1 = RegExp(r'\.\.');
                        RegExp reg2 = RegExp(r'\....');
                        RegExp reg3 = RegExp(r'\..\.');
                        if (reg1.hasMatch(newValue.text) ||
                            reg2.hasMatch(newValue.text) ||
                            reg3.hasMatch(newValue.text)) {
                            return oldValue;
                        }
                        else{
                            return newValue;
                        }
                      })
                    ],
  • Related