How to get rid from leading 0 (zero) in TextField

Viewed 133

How to remove 0 numbers without loosing your cursor position.

enter image description here

1 Answers
  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
    ],
    ...
  )
Related