4

How to remove 0 numbers without loosing your cursor position.

enter image description here

Kherel
  • 14,882
  • 5
  • 50
  • 80

3 Answers3

6
inputFormatters: [
        FilteringTextInputFormatter.digitsOnly,
        FilteringTextInputFormatter.deny(RegExp('^0+'))
      ]
Linar
  • 903
  • 6
  • 10
0
  TextField(
    controller: controller,
    onChanged: (value) {
      var selection = controller.selection;
      final RegExp regexp = new RegExp(r'^0+(?=.)');
      var match = regexp.firstMatch(value);

      var matchLengh = match?.group(0)?.length ?? 0;
      if (matchLengh != 0) {
        controller.text = value.replaceAll(regexp, '');
        controller.selection = TextSelection.fromPosition(
          TextPosition(
            offset: math.min(matchLengh, selection.extent.offset),
          ),
        );
      }
    },
    // keyboardType and inputFormatters not realy needed in this case but maybe usefull
    keyboardType: TextInputType.number,
    inputFormatters: <TextInputFormatter>[
      FilteringTextInputFormatter.digitsOnly
    ],
    ...
  )
Kherel
  • 14,882
  • 5
  • 50
  • 80
-1

you can also try to convert string into int or double to get rid out of leading zeros, like below example.

TextField(
  controller: controller,
  onChanged: (value) {
    controller.text = int.parse(value).toString();
  },
  inputFormatters: [
    FilteringTextInputFormatter.digitsOnly,
  ],
  ....
)
Shubhanshu Kashiva
  • 136
  • 1
  • 1
  • 7